A nested class is a class which is created inside another class. In Kotlin, the nested class is by default static, so its data member and member function can be accessed without creating an object of a class. The nested class cannot be able to access the data member of the outer class.
Kotlin Nested Class Example
package net.javaguides.kotlin
class outerClass {
private
var name: String = "outerClass"
class nestedClass {
var description: String = "code inside nested class"
private
var id: Int = 101
fun foo() {
// print("name is ${name}") // cannot access the outer class member
println("Id is ${id}")
}
}
}
fun main(args: Array < String > ) {
// nested class must be initialize
println(outerClass.nestedClass().description) // accessing property
var obj = outerClass.nestedClass() // object creation
obj.foo() // access member function
}
Output:
code inside nested class
Id is 101
Free Spring Boot Tutorial - 5 Hours Full Course
Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course