0
0
Kotlinprogramming~10 mins

Inner classes and nested classes in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a nested class inside the outer class.

Kotlin
class Outer {
    class [1] {
        fun greet() = "Hello from nested class"
    }
}
Drag options to blanks, or click blank then click option'
ANested
BCompanion
CInner
DStatic
Attempts:
3 left
💡 Hint
Common Mistakes
Using the keyword 'Inner' instead of 'Nested' for a nested class.
Trying to use 'Static' keyword which does not exist in Kotlin.
2fill in blank
medium

Complete the code to declare an inner class that can access the outer class's property.

Kotlin
class Outer {
    val greeting = "Hello"
    inner class [1] {
        fun greet() = greeting
    }
}
Drag options to blanks, or click blank then click option'
AInner
BNested
CCompanion
DStatic
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Nested' instead of 'Inner' when access to outer class properties is needed.
Forgetting the 'inner' keyword causes no access to outer class members.
3fill in blank
hard

Fix the error in the code to correctly create an instance of the inner class.

Kotlin
class Outer {
    inner class Inner {
        fun greet() = "Hi"
    }
}

fun main() {
    val inner = Outer().[1]()
    println(inner.greet())
}
Drag options to blanks, or click blank then click option'
AOuter
Bnew
Ccreate
DInner
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to instantiate inner class without an outer class instance.
Using keywords like 'new' which are not used in Kotlin.
4fill in blank
hard

Fill both blanks to create a nested class and call its method.

Kotlin
class Outer {
    class [1] {
        fun greet() = "Hello from nested"
    }
}

fun main() {
    val nested = Outer.[2]()
    println(nested.greet())
}
Drag options to blanks, or click blank then click option'
ANested
BInner
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Inner' keyword for nested class declaration.
Trying to instantiate nested class like an inner class.
5fill in blank
hard

Fill all three blanks to create an inner class, instantiate it, and call its method.

Kotlin
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]())
}
Drag options to blanks, or click blank then click option'
AInner
Cgreet
DNested
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Nested' instead of 'Inner' for the inner class.
Calling the method incorrectly or forgetting parentheses.