Showing posts with label nested classes. Show all posts
Showing posts with label nested classes. Show all posts

Tuesday, 9 January 2018

Kotlin: Nested classes

A class can be nested in other class.

Ex
class Outer {

         class Nested {

         }
}

How to create an object to nested class?
var obj = Outer.Nested()

NestedClass.kt
class Outer {

 fun printMsg() {
  println("Inside Outer class")
 }

 class Nested {
  fun printMsg() {
   println("Inside Nested class")
  }
 }
}

fun main(args: Array<String>) {
 var outerObj = Outer()
 var nestedObj = Outer.Nested()

 outerObj.printMsg()
 nestedObj.printMsg()
}

Output
Inside Outer class
Inside Nested class

Can I access the member variables defined in outer class from nested class?
No, you can’t access the member variables defined in outer class from nested class.


NestedDemo.kt

class Outer {
 private var x = 10

 class Inner {
  fun getX() = x
 }
}

When you try to compile above program, you will end up in below error.

Unresolved reference: x


Previous                                                 Next                                                 Home

Monday, 10 February 2014

Nested Classes

Java provides a facility like, you can define a class inside other class. This feature is called Nested classes.

    Example
    class OuterClass {
        class NestedClass {

        }
    }

Nested Classes can be static or non-static. A Nested class can be private, public, protected and default. Non-static nested classes are called inner classes.

    Example
    class OuterClass {   
        static class StaticNestedClass {

        }

        class InnerClass {

        }
    }

Uses Of Nested classes
1. Improve Encapsulation : We can make the nested classes as private, so outside world these nested classes are not visible.
2. More readable code : Making small nested classes and enclosing thse with outer classes, makes the code readable


final keyword                                                 static nested classes                                                 Home