Tuesday, September 12, 2017

Java Nested Classes

* Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.

* Static nested classesare accessed using the enclosing class name :                               OuterClass.StaticNestedClass

 For example, to create an object for the static nested class, use this syntax:


OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

* Inner Classes : Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:

class OuterClass {
    ...
    class InnerClass {
        ...
    }
}
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:


OuterClass.InnerClass innerObject = outerObject.new InnerClass();

there is also such a thing as an inner class without an enclosing instance:
class A {
  int t() { return 1; }
  static A a =  new A() { int t() { return 2; } };
}
* Local Inner ClassesA local inner class is a class declared in the body of a method. Such a class is only known within its containing method, so it can only be instantiated and have its members accessed within its containing method. The gain is that a local inner class instance is tied to and can access the final local variables of its containing method. When the instance uses a final local of its containing method, the variable retains the value it held at the time of the instance's creation, even if the variable has gone out of scope (this is effectively Java's crude, limited version of closures).


* Anonymous classes : Before Java had lambda expressions, anonymous inner classes were the most concise syntax available for providing runnables, comparators, and other functional
objects.

Reference : StackOverflow Discussion 

No comments:

Post a Comment

Thank you for your comment!