Quick summary on nested class
Nested classes are divided into two categories:
- static nested class
- non-static nested class (aka inner class)
|
|
Static Nested Class
- It is associated with its Outer class, not instances of the Outer class (same as any other static members)
- How to create an instance of it? 1OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
Non-static Nested Class (Inner class)
- It is associated with an instance of its Outer class and has direct access to that object’s methods and fields
- No static members are allowed in inner class except for constants (like
static final String NAME="Hello"
) - An instance of
InnerClass
can exist only within an instance ofOuterClass
- How to create an instance of it?12// must be created from an existing instance of the outer classOuterClass.InnerClass innerObject = outerObject.new InnerClass();
Static fields are not allowed in inner class. However, constants (static final members) are permitted.
|
|
Shadowing
|
|
Result:
|
|
References:
https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
https://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html