Inner class
Introduction : -
An inner class is a class that is defined within another class in object-oriented programming
languages like Java, Python, and others. The concept of inner classes allows you to logically group
classes that are only used in one place, increasing encapsulation and code organization.
Types of Inner Classes (Java Example):
1. Instance Inner Class:
o It is a class defined inside another class but outside any method.
o It can access the members of the outer class, including private ones.
o The instance of this inner class is associated with the instance of the outer
class.
class OuterClass {
private String message = "Hello from Outer Class!";
class InnerClass {
public void display() {
[Link](message); // Accessing outer class's private field
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
[Link] inner = [Link] InnerClass();
[Link]();
}
}
Static Inner Class:
Declared with the static keyword, a static inner class does not require an instance of
the outer class.
It can only access static members of the outer class.
class OuterClass {
private static String message = "Hello from Outer Class!";
static class InnerClass {
public void display() {
[Link](message); // Can access static members only
}
}
}
public class Main {
public static void main(String[] args) {
[Link] inner = new [Link]();
[Link]();
}
}
Local Inner Class:
Defined inside a method, it is only accessible within that method.
It can access the method’s local variables and the outer class's members.
class OuterClass {
void outerMethod() {
class LocalInnerClass {
void display() {
[Link]("Local Inner Class");
}
}
LocalInnerClass localInner = new LocalInnerClass();
[Link]();
}
}
public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
[Link]();
}
}
Anonymous Inner Class:
A class without a name, typically used to override methods of classes or interfaces.
Defined in place, often as an argument to a method.
class OuterClass {
void display() {
[Link]("Outer class display");
}
}
public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass() {
void display() {
[Link]("Anonymous Inner Class display");
}
};
[Link]();
}
}
Key Benefits of Inner Classes:
Encapsulation: Inner classes are a way to logically group classes that are used in one
place, enhancing modularity.
Access to outer class members: Inner classes can directly access outer class
members, including private members.
Enhanced readability: Since inner classes are part of their outer class, they make
code more readable when the relationship between classes is tight.