0
0
Kotlinprogramming~5 mins

Inner classes and nested classes in Kotlin

Choose your learning style9 modes available
Introduction

Inner and nested classes help organize code by grouping related classes together inside another class.

When you want to logically group a class inside another class to keep code tidy.
When the inner class needs to access members of the outer class.
When you want to create helper classes that are only used inside one main class.
When you want to avoid cluttering the top-level namespace with small classes.
Syntax
Kotlin
class Outer {
    class Nested {
        // Nested class code
    }

    inner class Inner {
        // Inner class code
    }
}

A nested class does not have access to the outer class's members.

An inner class can access the outer class's members and needs the inner keyword.

Examples
This is a nested class. It cannot access Outer class members.
Kotlin
class Outer {
    class Nested {
        fun greet() = "Hello from Nested"
    }
}
This is an inner class. It can access the outer class's name property.
Kotlin
class Outer(val name: String) {
    inner class Inner {
        fun greet() = "Hello from Inner, outer name is $name"
    }
}
Sample Program

This program shows how to create and use nested and inner classes. The nested class cannot access the outer class's name, but the inner class can.

Kotlin
class Outer(val name: String) {
    class Nested {
        fun greet() = "Hello from Nested"
    }

    inner class Inner {
        fun greet() = "Hello from Inner, outer name is $name"
    }
}

fun main() {
    val nested = Outer.Nested()
    println(nested.greet())

    val outer = Outer("Kotlin")
    val inner = outer.Inner()
    println(inner.greet())
}
OutputSuccess
Important Notes

Use inner keyword only when the inner class needs to access outer class members.

Nested classes are like static classes in other languages; they don't hold a reference to the outer class.

Inner classes hold a reference to the outer class instance, so be careful to avoid memory leaks.

Summary

Nested classes are defined inside another class but cannot access its members.

Inner classes use the inner keyword and can access outer class members.

Use inner classes when you need to work closely with the outer class's data.