0
0
Kotlinprogramming~5 mins

Inner classes and nested classes in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a nested class in Kotlin?
A nested class is a class defined inside another class without the <code>inner</code> keyword. It does not hold a reference to the outer class.
Click to reveal answer
beginner
What is an inner class in Kotlin?
An inner class is a class defined inside another class with the <code>inner</code> keyword. It holds a reference to an instance of the outer class and can access its members.
Click to reveal answer
beginner
How do you declare an inner class in Kotlin?
Use the <code>inner</code> keyword before the class name inside the outer class. For example:<br><pre>class Outer {
  inner class Inner {
    fun greet() = "Hello from Inner"
  }
}</pre>
Click to reveal answer
intermediate
Can a nested class access members of the outer class directly?
No, a nested class cannot access members of the outer class directly because it does not hold a reference to the outer class instance.
Click to reveal answer
intermediate
How can an inner class access the outer class members?
An inner class can access outer class members directly because it holds a reference to the outer class instance. You can also use <code>this@Outer</code> to refer to the outer class explicitly.
Click to reveal answer
Which keyword makes a class inside another class hold a reference to the outer class in Kotlin?
Astatic
Bnested
Couter
Dinner
Can a nested class in Kotlin access the outer class's properties directly?
ANo, never
BOnly if marked inner
CYes, always
DOnly if outer class is static
How do you create an instance of an inner class in Kotlin?
Aval inner = Outer.Inner()
Bval inner = Outer().Inner()
Cval inner = Inner()
Dval inner = new Outer.Inner()
What is the default nature of a nested class in Kotlin if no keyword is used?
AStatic nested class
BCompanion object
CAnonymous class
DInner class
Which expression refers explicitly to the outer class instance inside an inner class?
Athis
Bsuper
Cthis@Outer
Douter.this
Explain the difference between inner classes and nested classes in Kotlin.
Think about how each class relates to the outer class and their access to its members.
You got /5 concepts.
    Describe how to create and use an inner class instance in Kotlin.
    Remember the inner class needs the outer class instance to exist.
    You got /4 concepts.