Static Nested Class in Java – Definition, Syntax, and Example

Static Nested Class in Java | Definition, Syntax, Example & FAQs

Static Nested Class in Java

Definition

A Static Nested Class in Java is a nested class declared with the static keyword. It acts as a static member of the outer class.

  • It is a static member of the outer class.
  • Unlike inner classes, it does not require an instance of the outer class to be instantiated.
  • It can only access static members of the outer class directly.

Key Points

  1. Declared using the static keyword inside another class.
  2. Can directly access static data members of the outer class.
  3. Cannot access non-static members of the outer class without creating an object.
  4. Useful for logically grouping classes that are only used in one place.

Syntax


class OuterClass {
    static class StaticNestedClass {
        // Static nested class code here
    }
}
            

Example


class OuterClass {
    static int data = 50;

    static class Nested {
        void display() {
            System.out.println("Data from Outer Class: " + data);
        }
    }

    public static void main(String[] args) {
        OuterClass.Nested obj = new OuterClass.Nested();
        obj.display();
    }
}
            

Output:

Data from Outer Class: 50

Frequently Asked Questions (FAQs)

What is a static nested class in Java?
A static nested class is a static member class defined within another class that can be instantiated without an object of the outer class.
How does a static nested class differ from an inner class?
A static nested class cannot access non-static members of the outer class directly, whereas an inner (non-static) class can. Also, static nested classes do not require an instance of the outer class to be created.
Can static nested classes access non-static members of the outer class?
No, static nested classes can only directly access static members of the outer class.
When should I use a static nested class?
Use a static nested class when the nested class is closely related to the outer class and does not require access to instance variables or methods of the outer class.

Comments

Popular posts from this blog

Introduction to Java

Java Classes in Depth – Complete Guide with Definitions, Syntax & Examples

Top AI Tools for Social Media Marketing in 2025 – Automate & Grow Your Brand