Skip to main content

Kotlin Nested Class

Define of one class inside of another class that is called nested and inner class.

Nested class are define using following syntax.

class Outer {
    //define outer class data member and functions
    class Nested {
       //define Nested class data member and functions
    }
}

Nested class is more protect outside of the outer class. and help of outer class reference we are capable to access inner class properties.

class Outer {
    private var info:String ="Outer class"
    class Nested {
        private var message:String="Nested Class"
       
        fun display(){
            //display it's private data
            println(message)
        }
    }
}


fun main(args: Array) {
 
  val obj=Outer.Nested()
    obj.display() //access nested class function

}

Output

Nested Class

Outer Class name and dot operator is defined inner class object. but inside of nested class there in not possible to use outer class methods and properties. let see in this example

class Outer {
    private var info:String ="Outer class"
    class Nested {
        private var message:String="Nested Class"
       
        fun display(){
            
            println(info) //access outer class data member value
        }
    }
}


fun main(args: Array) {
 
  val obj=Outer.Nested()
    obj.display() //access nested class function

}

Error

source.kt:8:21: error: unresolved reference: info
            println(info) //access outer class data member value

resolve this problem using of inner class in kotlin.

Kotlin Inner class

class Outer {
    private var info:String ="Outer class"
    inner class InnerClass {
        private var message:String="Inner Class"
       
        fun display(){
            
            println(info) //access outer class data member value
        }
    }
}


fun main(args: Array) {
 
  val obj=Outer().InnerClass()
    obj.display() //access Inner class function

}

Output

Outer class




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment