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.
- Static nested class
- Non-static nested class
Example 1: Static nested class
x: 10 z: 30
Example 2: Non-static nested class
x: 10 y: 20 z: 30
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.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.