Complete the code to declare a nested class inside the outer class.
class Outer { class [1] { fun greet() = "Hello from nested class" } }
The keyword class Nested declares a nested class inside Outer. Nested classes do not hold a reference to the outer class.
Complete the code to declare an inner class that can access the outer class's property.
class Outer { val greeting = "Hello" inner class [1] { fun greet() = greeting } }
The inner keyword declares an inner class that holds a reference to the outer class instance, allowing access to its properties.
Fix the error in the code to correctly create an instance of the inner class.
class Outer { inner class Inner { fun greet() = "Hi" } } fun main() { val inner = Outer().[1]() println(inner.greet()) }
To create an instance of an inner class, you call it on an instance of the outer class like Outer().Inner().
Fill both blanks to create a nested class and call its method.
class Outer { class [1] { fun greet() = "Hello from nested" } } fun main() { val nested = Outer.[2]() println(nested.greet()) }
The nested class is declared with class Nested and called with Outer.Nested().
Fill all three blanks to create an inner class, instantiate it, and call its method.
class Outer { val message = "Hi from outer" inner class [1] { fun greet() = message } } fun main() { val outer = Outer() val inner = outer.[2]() println(inner.[3]()) }
The inner class is declared with inner class Inner, instantiated with outer.Inner(), and its method greet() is called.