- Defining a class within another class.
Why nested classes?
- A way of logically grouping classes that are only used in one place. If a class is useful to only one other class, then it is logical to embed in it, that class & keep the two together. Nesting makes their package more streamlined.
- It increases encapsulation. Consider 2 distinct classes A & B, where B is the only class that needs access to members of A, that would otherwise be declared private. By hiding class B within class A, A's members can be declared private & B can access them. In addition, B itself can be hidden from the outside world.
- Nesting places the code closer to the place where it is used. If class B is nested within class A, we can write another class 13 as a top-level class (ie., visible to the entire world). This has nothing to do with the one already present inside class A.
- If class B is nested within class A, then B is known to A, but not outside of A.
- A nested class can even access private members of the class in which it is nested.
- But enclosing class has no access to the members of the nested class.
- Since it is static, it cannot access the non-static members of its enclosing class directly (can be accessed only through an object). Thus, it is seldom used.
- The non-static nested class declared outside of any method of the outer class.
- Can access all the variables & methods of the outer class directly as other non-static methods of the outer class do.
Method-local Inner Class:
- Defined within a method of the enclosing class.
- For the inner class to be used, you must instantiate it & that instantiation must happen within the same method, but after the class definition code.
- Cannot use variables declared within the method (including parameters) unless those variables are marked final.
- Only modifiers that can be applied to a method-local inner class are abstract & final (but not both at the same time).
Anonymous Inner Classes:
- Inner classes declared without a name.
- Always created as part of a statement.