Nested Class
Nested classes are divided into two categories: static (static nested classes) and non-static (inner classes).
Static Nested Classes
- Static nested classes are 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();
- Static nested classes do NOT have access to other members of the enclosing class.
- As a member of the OuterClass, a nested class can be declared private, public, protected, or package private. (Recall that outer classes can only be declared public or package private.)
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();
The inner class is just a way to cleanly separate some functionality that really belongs to the original outer class. They are intended to be used when you have 2 requirements:
- Some piece of functionality in your outer class would be most clear if it was implemented in a separate class.
- Even though it's in a separate class, the functionality is very closely tied to way that the outer class works.
- Given these requirements, inner classes have full access to their outer class. Since they're basically a member of the outer class, it makes sense that they have access to methods and attributes of the outer class -- including privates.