Tuesday, July 18, 2017

Create an instance of the Inner class (Non-static nested class)

Non-static nested classes in Java are also called inner classes. Inner classes are associated with an instance of the enclosing class. Thus, you must first create an instance of the enclosing class to create an instance of an inner class. Here is an example inner class definition:
public class Outer {

  public class Inner {
  }

}
Here is how you create an instance of the Inner class:
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();

@reference_1_tutorials.jenkov.com
Java Nested Classes

Inner Class Shadowing (Hiding?)

If a Java inner class declares fields or methods with the same names as field or methods in its enclosing class, the inner fields or methods are said to shadow over the outer fields or methods. Here is an example:
public class Outer {

    private String text = "I am Outer private!";

    public class Inner {

        private String text = "I am Inner private";

        public void printText() {
            System.out.println(text);
        }
    }
}
In the above example both the Outer and Inner class contains a field named text. When the Inner class refers to text it refers to its own field. When Outer refers to text it also refers to its own field.
Java makes it possible though, for the Inner class to refer to the text field of the Outer class. To do so it has to prefix the text field reference with Outer.this. (the outer class name + .this. + field name) like this:
public class Outer {

    private String text = "I am Outer private!";

    public class Inner {

        private String text = "I am Inner private";

        public void printText() {
            System.out.println(text);
            System.out.println(Outer.this.text);
        }
    }
}
Now the Inner.printText() method will print both the Inner.text and Outer.text fields.

No comments:

Post a Comment