Inner Classes in Java
Inner Classes in Java:
Java supports four types of inner classes:
- Non-static Inner Class: Associated with an instance of the outer class and can access its members directly.
- A non-static inner class (also called a regular inner class) is a class defined inside another class without the
static
keyword. It has access to the instance variables and methods of the outer class. - Example:
- Static Nested Class: Similar to static methods; it does not require an instance of the outer class and can only access static members.
- A static nested class is a class defined inside another class using the
static
keyword. Unlike a non-static inner class, it does not require an instance of the outer class to be created. It behaves like a normal top-level class but is scoped inside the outer class. - Example:
- Method-local Inner Class: Defined within a method and can access local variables and parameters of the method if they are final or effectively final.
- A method-local inner class is a class defined inside a method of an outer class. It is created and used only within that method’s scope, similar to how a local variable behaves.
- Example:
- Anonymous Inner Class: A class defined without a name at the time of instantiation. It is often used to provide aone-time implementation of an interface or a subclass.
- An anonymous inner class in Java is a class without a name that is declared and instantiated in a single statement. It is mainly used when you need a one-time implementation of an interface, an abstract class, or even a concrete class.
- Example:
Quick Summary (Cheat Sheet- Which to use)
Non-static Inner Class → When it needs outer instance (tight coupling).
Static Nested Class → When it doesn’t need outer instance (looser coupling).
Method-local Inner Class → For temporary helper logic inside a method.
Anonymous Inner Class → For one-time use implementations (callbacks, threads, listeners).
Comments
Post a Comment