Kotlin - Inner Class Example

An inner class is a class which is created inside another class with keyword inner. In other words, we can say that a nested class which is marked as "inner" is called inner class.

Kotlin Inner Class Example

package net.javaguides.kotlin

class outerClass {
    private
    var name: String = "Ramesh"

    inner class innerClass {
        var description: String = "code inside inner class"
        private
        var id: Int = 101
        fun foo() {
            println("name is ${name}") // access the outer class member even private  
            println("Id is ${id}")
        }
    }
}

fun main(args: Array < String > ) {
    println(outerClass().innerClass().description) // accessing property  
    var obj = outerClass().innerClass() // object creation  
    obj.foo() // access member function  

}
Output:
code inside inner class
name is Ramesh
Id is 101

Comments