Last Updated: 20 November, 2023
A class that is defined inside another class with the static keyword is known as a static nested class in Java. A static nested class is not associated with any particular instance of the outer class. This means that a static nested class can be accessed and instantiated without having to create an instance of the outer class.
Static nested classes can access static members of the enclosing class, including private members as well, but static nested classes cannot access outer non-static properties directly.
Syntax: Static Nested Class in Java
Important points about Static Nested class in Java
A static nested class is a member of its enclosing class.
A static nested class can have static and non-static fields and methods.
A static nested class cannot access non-static members of its enclosing class.
A static nested class can access static members of its enclosing class, including private members.
An outer class will never be a static class in Java.
To access a static nested class, we can use the following syntax:
OuterClass.StaticNestedClass instance = new OuterClass.StaticNestedClass();
Here's an example of a static nested class in Java:
Example 1 : Static Nested Class implementation in Java
Output
num2 : 20
num1 : 10
OuterClass - display() method
Example 2 : Static Nested Class access Outer Class static properties
Output
OuterClass - static display() method
num : 20
That's all guys, hope this Java article is helpful for you.
Happy Learning.
feedback@javabytechie.com
Does Java support top-level classes as static?
Ans. No, Java does not allow us to define a top-level class as static, and if we try to do so, we will get a compile-time exception.
Let's see this scenario through the given example.
static class Test { void show() { System.out.println("show() method"); } } public class StaticOuterClass { public static void main(String[] args) { Test obj = new Test(); obj.show(); } }
Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Illegal modifier for the class A; only public, abstract & final are permitted at com.javabytechie.staticnestedclass.A(StaticOuterClass.java:3) at com.javabytechie.staticnestedclass.StaticOuterClass.main(StaticOuterClass.java:11)