Introduction Of Nested Class In Java
Nested Class
A class, which is declared inside the class or an interface is called as a nested class in Java.
If we use the nested classes to logically group of the classes and the interfaces in one place, it can be more readable, maintainable and can access all the members of the outer class (public, private and protected).
Syntax
class Java_Outer_class{
class Java_Inner_class{ // nested class
}
}
Advantages of nested classes in Java are,
There are many advantages of the nested classes in Java. They are given below.
- Nested classes show a special type of relationship, it can access all the member of the outer class including private.
- Nested classes are mainly used to build up our program more readable and maintainable because it logically groups the classes and the interfaces in one place only.
- Nested classes require less code to write.
How to differentiation between nested class and inner class in Java
In Java, all the inner classes are a part of the nested class and non-static nested classes are called as inner classes.
Types of Nested classes
In Java, two types of nested classes are,
- Non-static nested classes.
These classes are the non-static members of a class. - Static nested classes.
These classes are the static members of a class.
The non-static nested classes are also called as the inner classes.
Inner class (non-static nested class)
- Member inner class
- Annomynous inner class
- Local inner class
Static nested class
- Member inner class
This class is created within the class and outside the method. - Anonymous inner class
This class is created to implement an interface or extend the class. Its name is decided by the compiler. - Local inner class
This class is created within the method - Static nested class
This static class is created within the class - Nested interface
This interface created within the class or the interface
Summary
Thus, we learnt that a class, which is declared inside the class or an interface is called a nested class in Java and also learnt its types and advantage.