1.
Member Inner Class
A class defined inside another class (but outside any method). It is associated with an instance of
the outer class and can access its instance variables and methods (even private ones).
To logically group classes that are tightly coupled and to allow the inner class to access and
manipulate the outer class instance members directly.
Syntax to declare and instantiate object:
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
Example:
public class Outer {
private String message = "Hello from Outer";
class Inner {
void display() {
System.out.println(message);
}
}
public static void main(String[] args) {
Outer outer = new Outer(); // Create Outer instance
Outer.Inner inner = outer.new Inner(); // Create Inner tied to Outer
inner.display();
}
}
2. Static Nested Class
A static class defined inside another class. It cannot access non-static members of the outer class
directly.
Used when the nested class does not need access to outer class instance members but is still
logically grouped within the outer class.
Syntax to declare and instantiate object:
Outer.StaticNested nested = new Outer.StaticNested();
Example:
public class Outer {
private static String greeting = "Hello from Static Nested";
1
static class StaticNested {
void display() {
System.out.println(greeting);
}
}
public static void main(String[] args) {
Outer.StaticNested nested = new Outer.StaticNested(); // Direct
creation
nested.display();
}
}
3. Local Inner Class
A class defined inside a method or block. It is local to that method and cannot be accessed
outside it.
Syntax to declare and instantiate object:
void method() {
class LocalInner {
// class body
}
LocalInner local = new LocalInner();
}
Example:
public class Outer {
void method() {
class LocalInner {
void display() {
System.out.println("Hello from Local Inner");
}
}
LocalInner local = new LocalInner();
local.display();
}
public static void main(String[] args) {
Outer outer = new Outer();
outer.method();
}
}
2
4. Anonymous Inner Class
An inner class without a name, created in place at the point of declaration. Often used to
implement interfaces or extend classes inline.
To provide quick implementation of interfaces or abstract classes without creating a separate
named class file.
Syntax to declare and instantiate object:
InterfaceOrClass obj = new InterfaceOrClass() {
// Override methods here
};
Example:
public class Outer {
interface Greeting {
void sayHello();
}
public static void main(String[] args) {
Greeting greet = new Greeting() {
public void sayHello() {
System.out.println("Hello from Anonymous Inner Class");
}
};
greet.sayHello();
}
}