Kotlin Inner Class

A inner class can access members of outer class. It carries a reference to an object of an outer class. Just like nested class, it is created inside an outer class and unlike a nested class, it is marked with the keyword inner. It has advantages over nested class is that, it can access private members of outer class.

Example

fun main(args : Array<String>) {
    val x = Vehicle().car()
    x.about()
}
class Vehicle {
    private val name: String = "BMW"
    fun desc() {
        println("BMW AG is a German multinational company which 
				currently produces automobiles and motorcycles")
    }
    inner class car {
        var color: String = "Red"
        fun about() {
            println("Name of the car is ${name}")
            println("Description - ")
            desc()
        }
    }
}
Output
Name of the car is BMW
Description - 
BMW AG is a German multinational company which
currently produces automobiles and motorcycles.

In the above example, Vehicle is an outer class and car is an inner class which can access the properties and methods of outer class. In the main method, we have access the inner class method using the dot notation.







Read more articles


General Knowledge



Learn Popular Language