![]() |
VOOZH | about |
In Kotlin, you can define a class inside another class. Such classes are categorized as either nested classes or inner classes, each with different behavior and access rules.
A nested class is a class declared inside another class without the inner keyword. By default, a nested class does not have access to the members (fields or methods) of the outer class. This is similar to static nested classes in Java.
Syntax:
class OuterClass {
// Outer class members
class NestedClass {
// Nested class members
}
}
Nested class can't access the members of the outer class, but we can access the property of nested class from the outer class without creating an object for nested class.
Example:
Output:
250 horsepower, 6 cylindersIn Kotlin, to access the member function of nested class, we need to create the object for nested class and call the member function using it.
Kotlin classes are much similar to Java classes when we think about the capabilities and use cases, but not identical. Nested in Kotlin is similar to a static nested class in Java and the Inner class is similar to a non-static nested class in Java.
An inner class is a nested class marked with the inner keyword. Unlike nested classes, inner classes maintain a reference to their outer class and can access its members.
Example:
We need an instance of the outer class to create an instance of the inner class.
Example:
Output:
Outer class propertyIf we try to access an outer class property from an inner class without using the inner keyword, it will result in a compile-time error
Example:
Output:
Error: Unresolved reference 'str'.