Kotlin Nested Class

In Kotlin, we can create one class within the body of another class. It is called nested class. A nested class cannot access the data member of an outer class. It is static by default. So we can access its properties and methods without instantiating this.

class FirstClass {
	class SecondClass {
	
	}
}

We can provide the access level to the second class. If the SecondClass access level is private, then we can instantiate the SecondClass only within the scope of FirstClass. If we set the access level to protected, then only class that derived from the FirstClass would be able to create instances.

Example

class Animal {
    private val animaltype: String = "Pet"
    class Dog {
        fun legs() = 4
    }
}
fun main(args : Array<String>)  { 
	val legs = Animal.Dog().legs() 
    println("$legs")
}

Output

4

In the above example, we have created a Animal class and a nested class Dog inside it. In the main method, we have accessed the method of nested class. We cannot instantiate the nested class directly, so we call its method by using dot (.) notation to the outer class.







Read more articles