Introduce Java Inner Classes and give examples
Java Inner Classes are classes defined within the body of another class. They are a powerful feature of Java that allows for better organization of code and can help in logically grouping classes that are only used in one place. Inner classes can access the members (including private members) of the outer class, which can be very useful in certain scenarios.
There are four types of inner classes in Java:
Non-static Inner Class: This is a class defined within another class and is associated with an instance of the outer class.
Static Nested Class: This is a static class defined within another class. It does not have access to instance variables and methods of the outer class.
Method-local Inner Class: This is a class defined within a method of the outer class. It can access local variables of the method if they are declared final or effectively final.
Anonymous Inner Class: This is a class without a name that is defined and instantiated in a single statement. It is often used for implementing interfaces or extending classes on the fly.
class OuterClass {
private String outerField = "Outer Field";
class InnerClass {
void display() {
System.out.println("Accessing: " + outerField);
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.display(); // Output: Accessing: Outer Field
}
}
class OuterClass {
private static String staticOuterField = "Static Outer Field";
static class StaticNestedClass {
void display() {
System.out.println("Accessing: " + staticOuterField);
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass.StaticNestedClass nested = new OuterClass.StaticNestedClass();
nested.display(); // Output: Accessing: Static Outer Field
}
}
class OuterClass {
void outerMethod() {
final String localVariable = "Local Variable";
class MethodLocalInnerClass {
void display() {
System.out.println("Accessing: " + localVariable);
}
}
MethodLocalInnerClass inner = new MethodLocalInnerClass();
inner.display(); // Output: Accessing: Local Variable
}
}
public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
outer.outerMethod();
}
}
abstract class AbstractClass {
abstract void display();
}
public class Main {
public static void main(String[] args) {
AbstractClass anonymousInner = new AbstractClass() {
void display() {
System.out.println("Anonymous Inner Class");
}
};
anonymousInner.display(); // Output: Anonymous Inner Class
}
}
Java Inner Classes provide a way to logically group classes that are only used in one place, increase encapsulation, and allow for more readable and maintainable code. Each type of inner class has its own use cases and benefits, making them a versatile tool in Java programming.