Recall & Review
beginner
What is a nested class in Kotlin?A nested class is a class defined inside another class. In Kotlin, it does not hold a reference to the outer class by default.Click to reveal answer
beginner
How does a nested class differ from an inner class in Kotlin?A nested class is independent and cannot access members of the outer class. An inner class holds a reference to the outer class and can access its members.Click to reveal answer
beginner
Can a nested class access properties of its outer class in Kotlin?No, a nested class cannot access properties or functions of the outer class unless it is marked as inner.Click to reveal answer
intermediate
Why might you use a nested class instead of an inner class?Use a nested class when you want to group a class logically inside another but keep it independent, avoiding unnecessary references to the outer class.Click to reveal answer
intermediate
Show a simple Kotlin example of a nested class and explain its independence.class Outer {
class Nested {
fun greet() = "Hello from Nested"
}
}
// Usage:
val nested = Outer.Nested()
println(nested.greet())
// Explanation: Nested class does not access Outer members and can be created without an Outer instance.Click to reveal answer
In Kotlin, what does a nested class NOT have by default?
✗ Incorrect
A nested class does not hold a reference to the outer class instance unless marked as inner.
Which keyword makes a nested class able to access outer class members?
✗ Incorrect
The 'inner' keyword allows the nested class to access members of the outer class.
How do you create an instance of a nested class in Kotlin?
✗ Incorrect
A nested class instance is created using Outer.Nested() without needing an outer class instance.
Which statement is true about nested classes in Kotlin?
✗ Incorrect
Nested classes in Kotlin behave like static classes in Java, meaning they do not hold an implicit reference to the outer class.
Why might you avoid using inner classes when not needed?
✗ Incorrect
Inner classes hold a reference to the outer class, which can increase memory usage if not necessary.
Explain the difference between a nested class and an inner class in Kotlin.
Think about how each class relates to the outer class and what members they can access.
You got /4 concepts.
Describe a situation where using a nested class is better than an inner class.
Consider memory and design simplicity.
You got /4 concepts.