2- Nested class and Inner class
2- Nested class and Inner class
Nested Class
In Kotlin, you can define a class inside another class, which is known as a
nested class. Nested classes have access to the members (fields and methods)
of the outer class.
Kotlin
class Car {
var make: String
var model: String
var year: Int
fun main() {
val myCar = Car()
myCar.make = "Toyota"
myCar.model = "Camry"
myCar.year = 2020
println(engine.getEngineInfo())
}
Output:
class outerClass {
............
// outer class properties or member function
class nestedClass {
..........
// inner class properties or member function
}
}
Note: 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.
Kotlin
Output:
Praveen Ruhil
In 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
Output:
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.
Kotlin Inner Class
When we can declare a class inside another class using the keyword inner
then it is called inner class. With the help of the inner class, we can access the
outer class property inside the inner class.
class outerClass {
............
// outer class properties or member function
In the below program we are trying to access str from the inner class member
function. But it does not work and gives a compile-time error.
Kotlin program of inner class:
Kotlin
First, use the inner keyword in front of the inner class. Then, create an instance
of the outer class else we can’t use inner classes.
Kotlin
Output:
Advantages or Disadvantages: