Advertisement
Google Ad Slot: content-top
Java Inner Class
An inner class in Java is a class that is defined within another class. Inner classes have access to the members (fields, methods) of the outer class, even if they are private. Inner classes help logically group classes that are only used in one place, making your code more readable and maintainable.
Types of Inner Classes in Java:
There are four types of inner classes in Java:
- Non-static Inner Class (Member Inner Class)
- Static Nested Class
- Local Inner Class
- Anonymous Inner Class
Non-static Inner Class (Member Inner Class):
A non-static inner class is associated with an instance of the outer class. It can access the instance variables and methods of the outer class.
Syntax:
class OuterClass {
private int outerVar = 10;
class InnerClass {
void display() {
System.out.println("Outer variable: " + outerVar);
}
}
}
Static Nested Class:
A static nested class is a static member of the outer class. It can only access static members of the outer class. It does not need an instance of the outer class to be instantiated.
Syntax:
class OuterClass {
static int outerStaticVar = 20;
static class StaticInnerClass {
void display() {
System.out.println("Outer static variable: " + outerStaticVar);
}
}
}
Local Inner Class:
A local inner class is defined inside a method or a block of code, and it can only be used within that method/block. It cannot have access to the instance variables of the outer class unless they are declared final or effectively final.
Anonymous Inner Class:
An anonymous inner class is a special type of inner class that does not have a name. It is used to create instances of classes that may not be reused elsewhere. These classes are typically used to provide an implementation for interfaces or extend a class in a one-off manner.
- Abstract
- Interfaces