Java Inner Classes
Inner classes in Java are classes defined within another class. They are used to logically group classes that are only used in one place, increase encapsulation, and can lead to more readable and maintainable code.
Types of Inner Classes
1. Member Inner Classes
A member inner class is a class declared within another class and outside any method. It has access to all members of the outer class, including private ones.
Example:
public class OuterClass {
private int outerValue = 10;
public class InnerClass {
public void display() {
System.out.println("Outer value: " + outerValue);
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.display(); // Outputs: Outer value: 10
}
}
2. Static Nested Classes
A static nested class is a static class defined within another class. It does not have access to non-static members of the outer class.
Example:
public class OuterClass {
static int outerStaticValue = 20;
static class StaticNestedClass {
public void display() {
System.out.println("Outer static value: " + outerStaticValue);
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass.StaticNestedClass nested = new OuterClass.StaticNestedClass();
nested.display(); // Outputs: Outer static value: 20
}
}
3. Local Inner Classes
A local inner class is defined within a block, such as a method. It is only accessible within that block.
Example:
public class OuterClass {
public void outerMethod() {
class LocalInnerClass {
public void display() {
System.out.println("Inside local inner class");
}
}
LocalInnerClass lic = new LocalInnerClass();
lic.display();
}
}
public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
outer.outerMethod(); // Outputs: Inside local inner class
}
}
4. Anonymous Inner Classes
An anonymous inner class is a class without a name and is both declared and instantiated in a single statement. They are typically used to provide implementation of an interface or abstract class.
Example:
interface Greeting {
void sayHello();
}
public class Main {
public static void main(String[] args) {
Greeting greeting = new Greeting() {
@Override
public void sayHello() {
System.out.println("Hello from anonymous inner class!");
}
};
greeting.sayHello(); // Outputs: Hello from anonymous inner class!
}
}
Key Takeaways
- Inner classes can help logically group classes and increase encapsulation.
- Member inner classes have access to all members of the outer class.
- Static nested classes do not have access to non-static members of the outer class.
- Local inner classes are defined within methods and are only accessible there.
- Anonymous inner classes are useful for quick implementations, especially for interfaces or abstract classes.