-
Notifications
You must be signed in to change notification settings - Fork 22
Nested class vs Inner class
Devrath edited this page Feb 15, 2024
·
3 revisions
In Kotlin, nested classes and inner classes are two different concepts, and they are used to achieve different goals.
class OuterClass {
val outerClassMember = "outerClassMember"
fun outerClassFunction() { }
class NestedClass {
val nestedClassMember = "nestedClassMember"
fun nestedClassFunction() {
// This is not possible
// val nestedClassVariable = outerClassMember
// This is not possible
// outerClassFunction()
}
}
inner class InnerClass {
val innerClassMember = "innerClassMember"
fun innerClassFunction() {
// This is possible
val nestedClassVariable = outerClassMember
// This is possible
outerClassFunction()
}
}
}
A nested class in Kotlin is simply a class that is declared inside another class. It doesn't have access to the members of the outer class by default, and you can instantiate it without an instance of the outer class.
class OuterClass {
// Outer class members
class NestedClass {
// Nested class members
}
}
// Instantiating the nested class
val nestedInstance = OuterClass.NestedClass()
An inner class, on the other hand, is a class that is marked with the inner
keyword. It is a member of the outer class and can access the members of the outer class.
class OuterClass {
// Outer class members
inner class InnerClass {
// Inner class members can access the outer class members
}
}
// Instantiating the inner class
val innerInstance = OuterClass().InnerClass()
With an inner class, you can access the members of the outer class using this@OuterClass
syntax.
class OuterClass {
private val outerProperty: String = "Outer Property"
inner class InnerClass {
fun accessOuterProperty() {
println(this@OuterClass.outerProperty)
}
}
}
// Instantiating and using the inner class
val innerInstance = OuterClass().InnerClass()
innerInstance.accessOuterProperty()
- It can be useful in scenarios where the inner class is accessing some properties and implementation of the outer class.
- Without an existing Outer class, THe inner class cannot exist.
- Basically the inner class is tied to the outer class.
- Using the inner class we can group and keep the related logics together.
In summary:
- Nested class: Doesn't have access to the outer class by default.
-
Inner class: Has access to the members of the outer class and is marked with the
inner
keyword.
Choose between nested and inner classes based on whether you need access to the outer class members within the inner class.