androidengineers.Book a session

Object-Oriented Programming

Nested and Inner Classes

article15 minMedium

Be deliberate about outer-instance references

A nested class does not retain an enclosing instance. An inner class does, and can access the outer object's properties. That extra reference affects construction and lifetime.

class Course(val title: String) {
    class Tag(val name: String)
    inner class Summary {
        fun text(): String = "Course: $title"
    }
}

fun main() {
    val tag = Course.Tag("Kotlin")
    val course = Course("Foundations")
    println(course.Summary().text())
    println(tag.name)
}

Tag needs no course object, while Summary belongs to one. In Android, an inner helper that outlives an Activity can unintentionally retain that Activity. A nested helper with explicit dependencies often makes ownership clearer.

Do not use inner merely to shorten property access. Passing a string or interface may avoid retaining a much larger object graph.

Exercise

Rewrite Summary as a nested class receiving only the title. Compare its construction syntax and required dependencies.

Check: explain which objects remain reachable when each version of Summary is stored in a long-lived collection.

Reference: Nested and inner classes

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Nested and Inner Classes | Kotlin Core Programming | Android Engineers