In this guide, you will learn about nested and inner class in Kotlin with the help of examples.
Kotlin Nested Class
When a class is declared inside another class then it is called nested class. Nested classes are similar to static nested class in Java.
class OuterClass { .... class NestedClass { ... } }
Points to Note:
1. A Nested class cannot access the members of the outer class.
2. To access the members of nested class, we use the dot (.) operator with outer class.
Kotlin Nested Class Example
In the following example we have an outer class and a nested class. This example demonstrate how to access the members of nested class using dot (.) operator.
class OuterClass { val oStr = "Outer Class" class NestedClass { val nStr = "Nested Class" fun demo() = "demo() function of nested class" } } fun main(args: Array<String>) { // accessing data member of nested class println(OuterClass.NestedClass().nStr) // accessing member function of nested class println(OuterClass.NestedClass().demo()) // creating object of the Nested class val obj = OuterClass.NestedClass() println(obj.demo()) }
Output:
Kotlin Nested class – cannot access members of outer class
The following program will throw compilation error because a nested class does not have access to the members of outer class. Here the nested class is trying to access the member oStr which belongs to outer class, thus we are getting a compilation error. We can solve this issue by using inner class which is discussed in next section of this same article.
class OuterClass { val oStr = "Outer Class" class NestedClass { val nStr = "Nested Class" fun demo() = "demo() function using $oStr" } } fun main(args: Array<String>) { println(OuterClass.NestedClass().demo()) }
Output:
Compilation Error
Kotlin Inner class
Kotlin inner class is declared using inner
modifier. Inner classes have access to the members of the outer class. Lets take the same example that we have seen above using the inner class instead of nested class. Here we are accessing the member oStr
of outer class using the inside inner class.
class OuterClass { val oStr = "Outer Class" inner class InnerClass { val nStr = "Nested Class" fun demo() = "demo() function using $oStr" } } fun main(args: Array<String>) { val o = OuterClass() println("${o.InnerClass().demo()}") val i = OuterClass().InnerClass() println("${i.demo()}") }
Output:
Leave a Reply