Nested classes in Java
Java allows to define a class inside another class. When a class is nested inside a another class, it is said as nested class.
When nested classes can be used ?
- If a class needs to be used only in a single other class, you can nest that class inside the other class.
- If we need to increase the encapsulation or hiding data, we can use nested classes. By making the nested class as private, we can hide the nested class from the outer world.
- Nested classes also increases readability of a program when properly grouped.
General Syntax
class Outer_class{
class Inner_class{
//statements
}
}
Types of nested classes
- static nested class
- Non-static nested class or inner class