Java Nested_Inner_Classes
Java Nested_Inner_Classes
Inner Classes in
Java
Introduction
Java allows classes to be defined within other classes.
These are called Nested Classes.
They help in logically grouping classes and controlling visibility.
Nested classes can access out class members and improve code
modularity
Types of Nested Classes
class Outer {
static int a = 10;
static class StaticNested {
void show() {
System.out.println("Static a: " + a);
}
}
}
Usage:
Outer.StaticNested obj = new Outer.StaticNested();
obj.show();
Static Nested Class -
Advanced Example
class MathUtil {
static class Calculator {
static int square(int x) {
return x * x;
}
}
}
Usage:
int result = MathUtil.Calculator.square(5);
System.out.println(result); // 25
Static Nested Class -
Benefits
• Does not require access to outer class instance.
• Useful for grouping static helpers.
• Static nested classes allow you to organize related
static methods and constants within a containing
class.
• This helps keep your code more structured and
modular, especially for tools, calculators, or
common operations.
• Ideal for utility classes — classes that provide
commonly used static methods.
Inner Class - Basic
Example
•Non-static class defined inside another class.
•Can access both static and non-static members of the outer class.
•Needs an object of the outer class to be created.
class Outer {
int a = 10;
class Inner {
void display() {
System.out.println("a: " + a);
}
}
}
Usage:
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display();
Inner Class - Advanced
Example
class Bank {
private String bankName = "ABC Bank";
class Account {
void display() {
System.out.println("Welcome to " + bankName);
}
}
}
Usage:
Bank bank = new Bank();
Bank.Account acc = bank.new Account();
acc.display();
Advantages:
• Inner class has full access to outer class members.
• Ideal when the inner class depends heavily on the outer class for its functionality.
Local Inner Class
class Outer {
void outerMethod() {
class LocalInner {
void msg() {
System.out.println("Inside Local Inner Class");
}
}
LocalInner obj = new LocalInner();
obj.msg();
}
}
Key Points:
•Defined inside a method.
•Can access final or effectively final variables from method.
Anonymous Inner Class
abstract class Animal {
abstract void sound();
}
class Test {
public static void main(String args[]) {
Animal dog = new Animal() {
void sound() {
System.out.println("Woof Woof");
}
};
dog.sound();
}
}
When to use:
• When creating an instance of class with certain methods overridden.
• We need to redefining or implementing a method immediately while creating the object
• Useful for one-time use or quick custom behaviour
GUI Example with
Anonymous Inner Class
Anonymou
All members No One-time use
s
Best Practices