![]() |
VOOZH | about |
An inner class is a class declared inside the body of another class. The inner class has access to all members (including private) of the outer class, but the outer class can access the inner class members only through an object of the inner class.
class OuterClass {
// Outer class members
class InnerClass {
// Inner class members
}
Example:
Hello from Inner Class!
Java supports four types of inner classes:
A member inner class is a non-static class defined at the member level of another class. It has access to all members of the outer class, including private members.
Outer variable: 100
Before Java 16: member inner classes could NOT have static members (except static final constants).
After Java 16: Member inner classes CAN have static member, Only if they do not depend on an outer class instance
A method-local inner class is defined inside a method of the outer class. It can only be instantiated within the method where it is defined.
Inside outerMethod Inside innerMethod
Accessing Local Variables:
From Java 8 onwards, method-local inner classes can access effectively final or final local variables.
inside outerMethod x= 98
private, protected, static, or transient.abstract or final, but not both.A static nested class is a static class defined inside another class. It does not have access to instance members of the outer class but can access static members.
Static variable: 50
An anonymous inner class is an inner class without a name. It is declared and instantiated in a single statement. It is used to provide a specific implementation of a class or interface on the fly.
Types of Anonymous Inner Classes:
a) As a Subclass
Inside Demo's show method Inside Anonymous class
b) As an Interface Implementation
This is an inner method Inner variable: 20 Outer variable from inner class: 10