Lesson 31: Exploring Inner, Nested, and Anonymous Classes
Java allows defining a class inside another class. This helps group classes that are logically related and increases encapsulation.
1. Nested Classes
A class defined inside another class is called a nested class. They are divided into two main categories:
A. Static Nested Classes
- Declared with the
statickeyword. - They behave like static members: they can be accessed without an instance of the outer class.
- They can only access static members of the outer class.
java public class Outer { static class StaticNested { // Access only static members of Outer } } // Access: Outer.StaticNested nested = new Outer.StaticNested();
B. Inner Classes (Non-Static Nested Classes)
- Cannot be declared static.
- They are associated with an instance of the outer class.
- They have access to all members (static and non-static, even private) of the outer class.
java public class Outer { private int x = 10; class Inner { void display() { System.out.println("Outer x = " + x); // Accesses private member 'x' } } } // To create an Inner object, you need an Outer object first: // Outer.Inner inner = new Outer().new Inner();
2. Local Classes
Defined inside a method or block. Their scope is strictly limited to that block.
3. Anonymous Classes
A class without a name, used when you need to create an object of a class (or interface) that only needs to be used once.
java interface Printable { void print(); }
public class Example { public void doPrint() { // Anonymous class implementing Printable Printable p = new Printable() { @Override public void print() { System.out.println("Printing via anonymous class."); } }; p.print(); } }