A non-stationary inner class always needs an enclosing instance of the class in which it is nested. Inside the code defined in the Base class or Derived class (since it inherits the inner class), you can simply write
Nested nested = new Nested();
To create a new instance. Then you can call the getP () method on the nested link to get the value of the private value p. This value is part of an instance of the Base class that includes an Nested instance.
Because the inner class is publicly available, code defined outside of Base or Derived can also instantiate. But this requires an attached instance of Derived or Base. Java has special syntax for this, where you invoke a new statement on an instance of the enclosing class. So, outside of Base or Derived, you can do:
Base base = new Base(); Base.Nested baseNested = base.new Nested(); Derived derived = new Derived(); Derived.Nested derivedNested = derived.new Nested(); Base.Nested d = derivedNested;
You can also import Base.Nested so you can write:
Base base = new Base(); Nested baseNested = base.new Nested(); Derived derived = new Derived(); Nested derivedNested = derived.new Nested();
It's good to know this syntax, but I feel that the code is generally cleaner (easier to understand, better encapsulation), if only the closing class is allowed to create new instances of the inner class. You can also use a static nested class if you need a class that logically belongs only to Base but does not need a closing instance.
source share