java
- IntroductionInstallation and SetupJava Syntax and StructureRunning Your First ProgramJava VariablesData Types in JavaOperators in JavaJava Input and OutputControl StatementsLoops in JavaMethods in Java (Functions)Arrays in JavaString Handling in JavaOOPS Concept in JavaClasses and ObjectsConstructor and Constructor Overloadingthis KeywordStatic MembersInheritanceAggregation in JavaMethod OverloadingMethod Overridingsuper KeywordFinal Keyword with Class, Method, and VariablesAccess Modifiers in javaEncapsulation in Java Polymorphism in JavaAbstraction in JavaAbstract ClassesInterfaces in JavaDifference between Abstract Class and Interface Nested and Inner Classes Exception HandlingJava PackagesWrapper Classes and AutoboxingJava Collections FrameworkFile Handling in JavaMultithreadingBasics of Java Memory Management and Garbage CollectionJava JDBC
Nested and Inner Classes in Java – Full Tutorial for Beginners (With Examples)
Last Updated on: 22nd Nov 2025 19:03:56 PM
In Java, everything revolves around classes and objects. But sometimes, a single class is not enough to represent all the detailed behavior your program needs. To keep code clean, organized, and logically grouped, Java allows you to define a class inside another class. These are known as Nested and Inner Classes.
Nested classes help developers:
✔ Organize related classes together
✔ Hide unnecessary details from external classes
✔ Improve encapsulation and security
✔ Reduce the number of separate files
✔ Write compact and flexible code (especially in event handling)
You will find nested and inner classes used in real-world applications such as:
-
GUI frameworks (button click listeners)
-
Mobile apps (temporary actions, background tasks)
-
Banking systems (limited-scope helper classes)
-
File handling, multi-threading, and more
In this tutorial, we will explore all four types of nested classes—Inner, Static Nested, Local Inner, and Anonymous Inner Classes—with clear examples, real-life analogies, code, and outputs.
What Are Nested and Inner Classes?
In Java, you can define a class inside another class. These are called Nested Classes.
Java has 4 types of Nested Classes:
1️⃣ Inner Class (Non-Static Inner Class)
2️⃣ Static Nested Class
3️⃣ Local Inner Class
4️⃣ Anonymous Inner Class
Let’s understand each one easily.
1. Member Inner Class (Non-Static Inner Class)
This class is created inside another class, but outside any method. It requires an object of the outer class to access it.Also known as Regular Inner Class.
Characteristics
-
Can access all members of outer class, including private ones.
-
Needs an outer class object for creation.
Syntax:
class Outer {
class Inner {
}
}
Real-Life Example: Laptop → Keyboard
-
A Laptop always contains a Keyboard.
-
Keyboard cannot exist without laptop object.
Code Example
class Laptop {
class Keyboard {
void type() {
System.out.println("Typing using Laptop keyboard...");
}
}
}
public class Main {
public static void main(String[] args) {
Laptop laptop = new Laptop(); // Outer class object
Laptop.Keyboard kb = laptop.new Keyboard(); // Inner class object
kb.type();
}
}
OUTPUT
Typing using Laptop keyboard...
Example 2: Non-Static Inner Class
class Outer {
private String msg = "Welcome to ikeyskills!";
class Inner {
void show() {
System.out.println(msg);
}
}
}
public class Main {
public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.show();
}
}
Output
Welcome to ikeyskills!
2. Static Nested Class
A static nested class belongs to the outer class itself, not to an object of the class.
Characteristics
-
Declared using the static keyword.
-
Can access only static members of the outer class.
-
Does not need an object of the outer class to be created.
Code Example
class Outer {
static String message = "Hello from Outer!";
static class StaticNested {
void display() {
System.out.println("Message: " + message);
}
}
}
public class Main {
public static void main(String[] args) {
Outer.StaticNested obj = new Outer.StaticNested();
obj.display();
}
}
Output
Message: Hello from Outer!
Why Use Static Nested?
-
When the nested class does not depend on outer class objects.
-
Useful for grouping helper classes.
3. Local Inner Class (Inside Method)
A local inner class is defined inside a method.
Characteristics
-
Class defined inside a method
-
Scope is limited to the method where it is declared.
-
Cannot be accessed outside that method.
-
Can access local variables of the method if they are final or effectively final.
Code Example
class Outer {
void greeting() {
String name = "Sandip"; // effectively final
class LocalInner {
void display() {
System.out.println("Hello, " + name);
}
}
LocalInner obj = new LocalInner();
obj.display();
}
}
public class Main {
public static void main(String[] args) {
new Outer().greeting();
}
}
Output
Hello, Sandip
Real-Life Example: ATM Machine
Receipt class exists only during a transaction.
Code Example 2
class ATM {
void withdraw() {
class Receipt {
void show() {
System.out.println("Withdrawal Successful. Receipt printed.");
}
}
Receipt r = new Receipt();
r.show();
}
}
public class Main {
public static void main(String[] args) {
ATM atm = new ATM();
atm.withdraw();
}
}
OUTPUT
Withdrawal Successful. Receipt printed.
4. Anonymous Inner Class
An anonymous inner class is a class without a name that you create on the spot, usually to override methods.
Characteristics
-
Class without a name
-
Used for short-term implementation
-
Mostly used with Interfaces and Abstract Classes
-
Event handling (Swing, Android, etc.)
Code Example
interface Animal {
void sound();
}
public class Main {
public static void main(String[] args) {
Animal dog = new Animal() {
public void sound() {
System.out.println("Dog barks!");
}
};
dog.sound();
}
}
Output
Dog barks!
Real-Life Example: Button Click Listener
In Android, no need to create a separate class for click events.
Code Example 2
interface Payment {
void pay();
}
public class Main {
public static void main(String[] args) {
Payment p = new Payment() {
public void pay() {
System.out.println("Payment done via UPI.");
}
};
p.pay();
}
}
OUTPUT
Payment done via UPI.
Why Use Anonymous Inner Class?
✔ To quickly override a method
✔ Avoid creating separate class files
✔ Used in callbacks, event listeners
Why Use Nested & Inner Classes?
| Benefit | Explanation |
|---|---|
| ✔ Better Encapsulation | Inner class can access private members easily |
| ✔ Logical Grouping | Keep helper classes inside main classes |
| ✔ Cleaner Code | Avoid too many files |
| ✔ Writing Short, Temporary Code | Anonymous classes are perfect for quick logic |
When Should You Use Each?
Static Nested Class
When the nested class doesn’t use outer object members.
Inner Class
When you need tight coupling with outer class data.
Local Inner Class
When logic is method-specific.
Anonymous Inner Class
When you need a temporary class, mainly to override a method.
Complete Working Example (Real-Life Project Style)
// School Management System using Nested Classes
class School {
String schoolName = "Sunshine Academy";
// 1. Static Nested Class - Doesn't need school instance
static class Bus {
void pickStudents() {
System.out.println("School bus is picking students...");
}
}
// 2. Non-Static Inner Class - Belongs to a specific school
class Classroom {
int roomNo = 10;
void startClass() {
System.out.println("Class started in room " + roomNo + " at " + schoolName);
}
}
// 3. Method with Local & Anonymous Class
void conductExam() {
String subject = "Mathematics";
// Local Inner Class
class ExamPaper {
void distribute() {
System.out.println("Distributing " + subject + " paper...");
}
}
ExamPaper paper = new ExamPaper();
paper.distribute();
// Anonymous Class (for result announcement)
Runnable announceResult = new Runnable() {
@Override
public void run() {
System.out.println("Results of " + subject + " announced at " + schoolName);
}
};
announceResult.run();
}
}
public class SchoolDemo {
public static void main(String[] args) {
System.out.println("=== School System ===\n");
// Static Nested
School.Bus bus = new School.Bus();
bus.pickStudents();
// Inner Class
School school = new School();
School.Classroom room = school.new Classroom();
room.startClass();
// Local + Anonymous
school.conductExam();
}
}
Output:
=== School System ===
School bus is picking students...
Class started in room 10 at Sunshine Academy
Distributing Mathematics paper...
Results of Mathematics announced at Sunshine Academy
Quick Comparison Table
| Type of Nested Class | Keyword | Needs Outer Object? | Can Be Static? | Use Case |
|---|---|---|---|---|
| Member Inner Class | none | ✔ Yes | ❌ | Strong HAS-A relationship |
| Static Nested Class | static | ❌ No | ✔ | Independent component |
| Local Inner Class | inside method | ✔ | ❌ | Logic limited to method |
| Anonymous Inner Class | none | ✔ | ❌ | One-time use implementation |
Final Summary
-
Java allows you to write classes inside classes → Nested Classes
-
They improve structure, encapsulation, and readability
-
Four types:
Inner Class
Static Nested Class
Local Inner Class
Anonymous Inner Class
These concepts help you write more organized, modular, and readable Java code — perfect for real-world applications.
Keep practicing — you're doing amazing!
Happy Coding! ![]()
.png)