Kotlin Nested class and Inner class
In this blog, we will learn about nested class and Inner Class working.
A class is declared within another class then it is called a nested class. By default nested class is static so we can access the nested class property or variables using dot(.) notation without creating an object of the class.
Koltin program of accessing nested class member function:
class parentClass {
var userInfo = "Amen"
class childClass {
val firstName = "Om"
fun calculation() {
val principal = 10000
val rate = 6
val time = 2
val simpleInterest = principal * rate * time / 100
println("Simple interest is : $simpleInterest")
}
fun nestFunction(str2: String): String {
var s2 = firstName.plus(str2)
return s2
}
}
}
fun main() {
// creating object of Nested class
val obj = parentClass.childClass()
obj.calculation()
val combineName = obj.nestFunction("Shankar")
println("Full Name: $combineName")
// accessing member of Nested class
println("First Name :" + parentClass.childClass().firstName)
}
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.
Comparison with Java
Kotlin classes are much similar to Java classes when we think about the capabilities and use cases, but not identical. Nested in Koltin 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.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.
class parentClass {
var userInfo = "Amen"
inner class childClass {
val firstName = "Om"
fun calculation() {
val principal = 10000
val rate = 6
val time = 2
val simpleInterest = principal * rate * time / 100
println("Simple interest is : $simpleInterest")
}
fun nestFunction(str2: String): String {
var s2 = firstName.plus(str2)
var s3= firstName.plus(userInfo)
return s2
}
}
}
fun main() {
// creating object of Nested class
val obj = parentClass().childClass()
obj.calculation()
val combineName = obj.nestFunction("Shankar")
println("Full Name: $combineName")
// accessing member of Nested class
println("First Name :" + parentClass().childClass().firstName)
}