Javatpoint Logo
Javatpoint Logo

Difference Between Static and Non-Static Nested Class in Java

In the Java programming language, nested classes are classes that are defined within another class. These nested classes can be classified into two types: static nested classes and non-static nested classes, which are also referred to as inner classes. Their main difference lies in their relationship with the enclosing class and their access to instance variables and methods. Static nested classes are commonly used to logically group related utility classes or provide a convenient way of packaging-related functionality. Non-static nested classes are often used when there is a strong relationship between the nested class and its enclosing class, and they can be useful for implementing complex data structures or maintaining encapsulation.

Static Nested Class:

In Java, a static nested class refers to a class defined within another class using the static keyword. It is distinct from non-static nested classes (inner classes) in that it does not depend on any instance of the outer class and can be accessed independently. It can be accessed and instantiated without requiring an outer class instance.

Filename: OuterClass.java

Output:

Outer static field: 10
Nested field: 30
Outer static field: 10
Nested field: 40
Outer static field: 10
Nested field: 50

Non-Static (Inner) Nested Class

A non-static nested class in Java, also known as an inner class, is a class that is defined inside another class and is not marked with the static keyword. In Java, non-static nested classes, also known as inner classes, are intricately linked to an instance of the outer class, granting them direct access to its instance members. Inner classes can refer to and modify the instance variables and methods of the outer class without the need for explicit references. They provide a way to logically group classes together and enable them to interact more closely with each other.

Filename: OuterClass.java

Output:

Outer instance field: 10
Inner instance field: 20

Difference between Static Nested Class and Non-Static (Inner) Class

Static Nested Class Non-Static (Inner) Class
Can be instantiated independently Requires an instance of the outer class
Independent of any instance of the outer class Tightly associated with an instance of the outer class
Can access static members directly Can access both static and non-static members
Cannot access instance fields directly Can access instance fields directly
Cannot invoke non-static methods Can invoke both static and non-static methods
Cannot access non-static nested classes Can access both static and non-static nested classes






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA