Nested classes

If you have worked with C# or Java, you're likely to be already familiar with the declaration of a class inside a class. Kotlin provides a similar feature with more functionalities, which is useful when we need to encapsulate the functionalities of one class. Let's start with normal nested classes. Create a class called Outer with one property, out, and one function, info(). Now, create a nested class called Nested with one property, nest, and one function, info(). Both of the info functions in the Outer and Nested classes display messages on the screen:

class Outer{

val out = "Outer class"

fun info() {
println("I am an outer class function")
}

fun getNestedClass() : Nested{
return Nested()
}

class Nested {
val nest = "Nested class"
fun info() {
println("I am a nested class function")
}
}
}

We can create an instance of the Outer class as we did before. To create an instance of the Nested class, however, we must use the Outer class name as a reference:

fun main(args: Array<String>){

val outerObj = Outer()
println(outerObj.out)
outerObj.info()

var nestedObj = Outer.Nested()
println(nestedObj.nest)
nestedObj.info()

nestedObj = outerObj.getNestedClass()
println(nestedObj.nest)
nestedObj.info()
}

The main function contains outerObj, which is an instance of the outer class that can access its own properties. To create an instance of the Nested class, however, we have to use the Outer class name as a reference. Once the class object is created, we can use it as a normal object to utilize class members.

We can get the instance of the Nested class from the Outer class by creating a function:

class Outer{
:::::::
fun getNestedClass() : Nested{
return Nested()
}
class Nested {
::::::::
}
}
fun main(args: Array<String>){

val outerObj = Outer()
println(outerObj.out)
outerObj.info()

var nestedObj = Outer.Nested()
println(nestedObj.nest)
nestedObj.info()

nestedObj = outerObj.getNestedClass()
println(nestedObj.nest)
nestedObj.info()
}

The Nested class is not accessible if it is declared as private:

private class Nested {
val nest = "Nested class"
fun info() {
println("I am a nested class function")
}
}

It is very important to notice that neither the inner nor the outer class can access the members of the other class. If we want to access the members of the inner class, we must define it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.163.180