Difference Between Static and Non Static Nested Class in Java
Nested classes are divided into two categories namely static and non-static. Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes.
A class can either be static or non-static in java. So there is a lot of difference between making a class static or non-static. There are two kinds of classes in Java, one is called a top-level class and the other is called a nested class. As the name suggested top-level class is a class that is declared in ‘.java’ file.
On the other hand, a nested class is declared inside another class. The class which enclosed nested class is known as Outer class. In the Java programming language, you can not make a top-level class static. You can only make nested classes either static or non-static. If you make a nested class non-static then it also referred to as Inner class.
User-cases:
Example 1: Static nested class
Java
import java.io.*;
import java.util.*;
class ClassA {
static int x = 10 ;
int y = 20 ;
private static int z = 30 ;
static class ClassB {
void get()
{
System.out.println( "x: " + x);
System.out.println( "z: " + z);
}
}
}
class GFG {
public static void main(String[] args)
{
ClassA.ClassB ob1 = new ClassA.ClassB();
ob1.get();
}
}
|
Example 2: Non-static nested class
Java
import java.io.*;
class ClassA {
static int x = 10 ;
int y = 20 ;
public int z = 30 ;
class ClassB {
void get()
{
System.out.println( "x: " + x);
System.out.println( "y: " + y);
System.out.println( "z: " + z);
}
}
}
class GFG {
public static void main(String[] args)
{
ClassA ob1 = new ClassA();
ClassA.ClassB ob2 = ob1. new ClassB();
ob2.get();
}
}
|
Now the difference between Static and Non-Static Nested Class in Java:
- The static inner class can access the static members of the outer class directly. But, to access the instance members of the outer class you need to instantiate the outer class.
- Nested static class doesn’t need a reference of Outer class but a nonstatic nested class or Inner class requires Outer class reference.
- A non-static nested class has full access to the members of the class within which it is nested. A static nested class does not have a reference to a nesting instance, so a static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested.
- Another difference between static and non-static nested class is that you can not access non-static members e.g. method and field into nested static class directly. If you do you will get errors like “nonstatic member can not be used in the static context”. While the Inner class can access both static and non-static members of the Outer class.
Last Updated :
19 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...