Course contentsShow
← Java
Lesson 615 of 2,87015. Nested and Inner ClassesFree lesson

Declaring and Instantiating Static Nested Classes

Learn the syntax for declaring static nested classes and creating instances using OuterClass.NestedClass syntax.

Declaring and Instantiating Static Nested Classes

You'll learn: How to write the syntax for defining a static nested class and creating instances of it using the OuterClass.NestedClass format.

The Core Syntax

A static nested class is declared inside another class using the static keyword. Here's the basic structure:

public class OuterClass {
    
    static class NestedClass {
        // Fields and methods go here
    }
}

The key detail: you declare it just like a regular class, but place it inside another class with the static modifier before the class keyword.

Creating Instances

The instantiation syntax differs from regular classes. You use the fully-qualified name with the outer class as a prefix:

OuterClass.NestedClass instance = new OuterClass.NestedClass();

Notice you don't need an instance of OuterClass to create a NestedClass object. The static keyword means the nested class exists independently—it's associated with the outer class type, not any particular outer class instance.

A Practical Example

public class University {
    
    static class Department {
        private String name;
        
        public Department(String name) {
            this.name = name;
        }
        
        public String getName() {
            return name;
        }
    }
}

// Elsewhere in your code:
University.Department cs = new University.Department("Computer Science");
System.out.println(cs.getName());  // Prints: Computer Science

No University object needed! The Department class is logically grouped with University but operates independently.

Why the Dot Notation?

Think of it like a filing system: University.Department tells Java "look for the Department class inside the University namespace." It keeps related classes organized without requiring object relationships.

Key Takeaway: Declare static nested classes with static class NestedClass inside the outer class, and instantiate them using OuterClass.NestedClass instance = new OuterClass.NestedClass() without needing an outer class instance.