CoderSathi
  • Tutorial
    • Java Tutorial
    • Swing Tutorial
    • JDBC Tutorial
    • Java String Tutorial
    • Servlet and JSP Tutorial
  • Mongo DB
  • AWS
  • DevOps
  • Linux
  • Git
Home > Java > Nested and Inner Class in Java

Java Tutorial

  • Introduction
    • What is Java
    • History Of Java
    • Install Java
    • What is JVM
    • JDK vs JRE vs JVM
    • Java Bytecode
    • OOP vs POP
    • Compile and Run Java
  • Tokens, Expressions and Control Structures
    • Primitive data types
    • Integers
    • Floating Points
    • Characters
    • Booleans
    • User Defined Data Type
    • Declarations
    • Constants
    • Identifiers
    • Literals
    • Type Conversion and Casting
    • Variables
    • Default Variable Initialization
    • Command Line Arguments
    • Arrays of Primitive Types
    • Comment Syntax
    • Garbage Collection
    • Expressions
    • Operators
    • Arithmetic Operator
    • Bitwise and Shift Operator
    • Comparison or Relational Operators
    • Logical Operators
    • Assignment Operators
    • Ternary Operator
    • Increment and Decrement Operator
    • Control Statements
  • OOP Concepts
    • Class and Object
    • Create Class Instance
    • Method
    • Abstraction
    • Encapsulation
    • this keyword
    • Constructor
    • Pass by Value
    • Access Modifier/Control
    • Polymorphism
    • Method Overloading vs Method Overriding
    • Recursion
    • Nested and Inner Class
  • Inheritance and Packaging
    • Inheritance
    • extends Keyword
    • super Keyword
    • Object Class
    • Abstract class
    • Final Class
    • Java Package
    • Interface
  • Handling Error/ Exceptions
    • What is Exception
    • Exception Handling Keywords
    • Common Java Errors
    • User Defined Exception
    • Throwing and re-throwing Exception
    • finally Block
  • Strings
    • Java String Tutorial
  • Threads
    • Introduction
    • Create Thread
    • Thread Lifecycle
    • Thread Priority
    • Thread Synchronization
    • Inner Thread Communication
    • Thread Deadlock
  • IO and Streams
    • java.io Package
    • Files and Directories
    • Byte Stream
    • Character Stream
    • Console Input and Output
    • Serializable and Deserializable
  • Core Packages
    • java.lang Package
    • Math
    • Wrapper Classes
    • java.lang.Number
    • Double
    • Float
    • Integers
    • java.lang.Byte
    • java.lang.Short
    • java.lang.Long
    • java.lang.Character
    • java.lang.Boolean
    • java.util package
    • Vector Class
    • Stack Class
    • Dictionary Class
    • Hashtable
    • Enumeration or Enum
    • Generate Random Number
  • Holding Collection of Data
    • Arrays
    • Map
    • List
    • Set
    • Collection Interface
    • Collections Class
    • ArrayList
    • HashSet
    • TreeSet
    • Comparator
  • Java Bean
    • What is Java Bean
    • Advantages and Disadvantages of Java Bean
    • Java Beans API
    • Introspection
    • Java Bean Properties
    • Bound and Constrained Properties
    • BeanInfo Interface
    • Customizers
    • Java Beans Persistence
    • BeanDescriptor
  • Home

Nested and Inner Class in Java

Learn the concepts, implementation details, and practical steps with a clean developer-focused walkthrough.

Yuba Raj Kalathoki
By Yuba Raj Kalathoki
Last updated: July 1, 2026 · 4 min read · 0 Comments
Share: in X

Nested classes in Java allow you to define a class within another class, promoting encapsulation and logical grouping. From static nested classes to anonymous inner classes, each type serves unique purposes. In this guide, you’ll learn how and when to use them, along with practical examples and best practices.

Table of Contents

  • What Are Nested Classes?
  • 1. Static Nested Classes
    • Example:
  • 2. Non-Static Inner Classes
    • Example:
  • 3. Local Inner Classes
    • Example:
  • 4. Anonymous Inner Classes
    • Example (Runnable Interface):
  • Comparison of Nested Classes
  • Common Mistakes (and Fixes)
    • 1. Instantiating Non-Static Inner Class Without Outer Instance
    • 2. Accessing Non-Final Variables in Local/Anonymous Classes
  • Best Practices
  • Conclusion
  • FAQs
    • Can a nested class be private or protected?
    • Can nested classes extend other classes?
    • Why use inner classes over static nested classes?

What Are Nested Classes?

A nested class is a class declared inside another class. It’s used to:

  • Group related classes.
  • Enhance encapsulation.
  • Improve code readability.

Java supports four types of nested classes:

  1. Static Nested Classes
  2. Non-Static (Inner) Classes
  3. Local Inner Classes (inside methods/blocks)
  4. Anonymous Inner Classes (no name)

1. Static Nested Classes

A static nested class is associated with the outer class but doesn’t require an instance of it.

Example:

public class University {  
    static class Student {  
        String name;  
        Student(String name) { this.name = name; }  
    }  

    public static void main(String[] args) {  
        // Instantiate without University object  
        Student student = new Student("Alice");  
        System.out.println(student.name); // Output: Alice  
    }  
}  

When to Use:

  • For logical grouping of classes (e.g., University.Student).
  • When the nested class doesn’t need access to outer class instance variables.

2. Non-Static Inner Classes

An inner class is tied to an instance of the outer class and can access its members.

Example:

public class LinkedList {  
    private Node head;  

    class Node { // Inner class  
        int data;  
        Node next;  

        Node(int data) {  
            this.data = data;  
            next = head;  
            head = this; // Access outer class field  
        }  
    }  

    public static void main(String[] args) {  
        LinkedList list = new LinkedList();  
        list.new Node(10); // Instantiate via outer class instance  
    }  
}  

When to Use:

  • When the nested class needs direct access to the outer class’s fields/methods.
  • For helper classes (e.g., Node in LinkedList).

3. Local Inner Classes

A local inner class is defined within a method or block and is only accessible there.

Example:

public class Outer {  
    void display() {  
        class Local { // Local inner class  
            void print() { System.out.println("Local class"); }  
        }  
        Local local = new Local();  
        local.print();  
    }  

    public static void main(String[] args) {  
        Outer outer = new Outer();  
        outer.display(); // Output: Local class  
    }  
}  

When to Use:

  • For one-off utilities inside a method.

4. Anonymous Inner Classes

An anonymous inner class has no name and is declared/instantiated in a single step. Often used for event listeners.

Example (Runnable Interface):

public class AnonymousDemo {  
    public static void main(String[] args) {  
        Runnable r = new Runnable() { // Anonymous class  
            @Override  
            public void run() {  
                System.out.println("Running!");  
            }  
        };  
        new Thread(r).start(); // Output: Running!  
    }  
}  

When to Use:

  • For quick implementations of interfaces or abstract classes (e.g., GUI event handling).

Comparison of Nested Classes

TypeAccess Outer MembersStaticInstantiation
Static Nested❌ No (unless static)✅ YesOuter.StaticNested obj = new Outer.StaticNested();
Inner (Non-Static)✅ Yes❌ NoOuter outer = new Outer(); Outer.Inner inner = outer.new Inner();
Local Inner✅ Yes (final vars)❌ NoInside method/block only.
Anonymous Inner✅ Yes (final vars)❌ NoInline during object creation.

Common Mistakes (and Fixes)

1. Instantiating Non-Static Inner Class Without Outer Instance

Error:

Outer.Inner inner = new Outer.Inner(); // Error  

Fix:

Outer outer = new Outer();  
Outer.Inner inner = outer.new Inner();  

2. Accessing Non-Final Variables in Local/Anonymous Classes

Error:

void method() {  
    int count = 0;  
    Runnable r = () -> System.out.println(count++); // Error: count not final  
}  

Fix: Declare variables as final or use effectively final variables.

Best Practices

  1. Prefer Static Nested Classes: Unless you need access to outer instance fields.
  2. Limit Anonymous Classes: Use lambdas for functional interfaces (Java 8+).
  3. Keep Local Classes Short: Avoid cluttering methods with long class definitions.

Conclusion

Nested and inner classes in Java enhance encapsulation and organization. By choosing the right type (static, inner, local, or anonymous), you’ll write cleaner, more modular code.

FAQs

Can a nested class be private or protected?

Yes. Use access modifiers to control visibility.

Can nested classes extend other classes?

Yes. They behave like regular classes but with access restrictions.

Why use inner classes over static nested classes?

When the nested class needs direct access to the outer class’s instance variables.

Related Posts:

  • Encapsulation in Java
  • Access Modifiers in Java
  • Interface in Java: Mastering Abstraction and…
  • Abstract Class in Java: Bridging Code Reusability…
  • Control Statements in Java
  • Default Variable Initialization in Java
Tags:javalanguage-fundamentals
Was this article helpful?
← Previous ArticleRecursion in Java
Next Article →Inheritance in Java: A Developer’s Guide to Code Reusability

Leave a Comment Cancel reply

You must be logged in to post a comment.

Recent Posts

  • How to implement Passwordless Authentication in Spring Boot: A Step-by-Step Guide
  • How to Use AWS CloudFront Signed URLs in Spring Boot?
  • How to Fix SSH Agent Forwarding on macOS: The Ultimate Guide for Developers
  • How to Read AWS Secrets Manager in Spring Boot (Step-by-Step)
  • How to Fix “Public Key Retrieval is not allowed” MySQL JDBC Error
CoderSathi

Your go-to resource for Java, Spring Boot, Microservices, AWS, and modern development tutorials.

Linkedin

Quick Links

  • About
  • Contact

Popular Topics

  • Java
  • Spring Boot
  • AWS
  • DevOps
  • MongoDB
  • Linux
  • Git
  • How to
© 2026 CoderSathi. All rights reserved. Privacy Policy · Sitemap