In this article we are going to more about kotlin class and object with Inner and Nested class.
Nested Class:
Class which is created inside another class, is called as a nested class. Nested Class in kotlin, can be accessed without creating any object of that class, because it is by default static.
Note: Kotlin nested Class is similar to static nested class in Java.
Example:
class outerClass { val a = "Outside Of Nested class." class nestedClass { val b = "Inside Nested class." fun callMe() = "Function, inside Nested class." } } fun main(args: Array<String>) { // accessing member of Outer Class println(outerClass().a) // accessing member of Nested Class println(outerClass.nestedClass().b) // creating object of Nested Class val nested = outerClass.nestedClass()
// accessing function of Nested Class
println(nested.callMe())
}
Outside Of Nested class.
Inside Nested class.
Function, inside Nested class.
Inner Class:
Inner class is a nested class which is marked with an "Inner" keyword. Once you marked a nested class with an "Inner", you will not have to create an objet object for Nested class.
Example.
class outerClass { val a = "Outside Of Nested class." inner class nestedClass { fun callMe() = a } } fun main(args: Array<String>) { val obj = outerClass() println(obj.nestedClass().callMe()) }
Output:
Outside Of Nested class."
Comments
Post a Comment