0
0
Kotlinprogramming~5 mins

Nested class independence from outer in Kotlin

Choose your learning style9 modes available
Introduction

Nested classes in Kotlin are like small boxes inside a bigger box. They work on their own and don't need the bigger box to do their job.

When you want to group related classes together but keep them separate in behavior.
When the inner class does not need to access the outer class's properties or functions.
When you want to organize code clearly without mixing responsibilities.
When you want to avoid accidental access to outer class members from the nested class.
Syntax
Kotlin
class Outer {
    class Nested {
        fun greet() = "Hello from Nested"
    }
}

A nested class in Kotlin is declared with the class keyword inside another class.

By default, nested classes do not have access to the outer class's members.

Examples
The nested class Nested cannot access outerName directly.
Kotlin
class Outer {
    val outerName = "Outer"
    class Nested {
        fun nestedGreet() = "Hi from Nested"
    }
}
An inner class can access the outer class's properties, unlike a nested class.
Kotlin
class Outer {
    val outerName = "Outer"
    inner class Inner {
        fun innerGreet() = "Hi from $outerName"
    }
}
You create an instance of a nested class using Outer.Nested() without needing an outer class instance.
Kotlin
fun main() {
    val nested = Outer.Nested()
    println(nested.nestedGreet())
}
Sample Program

This program shows that the nested class works independently and prints its own message.

Kotlin
class Outer {
    val outerMessage = "Outer class message"

    class Nested {
        fun nestedMessage() = "Nested class message"
    }
}

fun main() {
    val nested = Outer.Nested()
    println(nested.nestedMessage())
    // The nested class cannot access outerMessage directly
}
OutputSuccess
Important Notes

Remember, nested classes do not hold a reference to the outer class instance.

If you want the inner class to access outer class members, use the inner keyword.

Summary

Nested classes are independent and do not access outer class members.

They help organize code without mixing responsibilities.

Use inner classes if you need access to outer class properties.