Nested class in Java
Nested class in Java
Java allows you to define a class inside another class; these are called nested classes. They boost the use of encapsulation and produce more understandable and manageable code by allowing you to logically arrange classes that are only used in one location.
A nested class's scope is limited by the enclosing class's scope. As a result, the class NestedClass in the example below does not exist separately from the class OuterClass. The members of the class in which it is nested, including private members, are accessible to a nested class. However, the member of the nested class is not accessible to the enclosing class.
A nested class belongs to its encompassing class as well. A nested class may be declared private, public, protected, or package-private (default) as a member of its enclosing class.
Nested classes are divided into two categories:
- static nested class: Nested classes that are declared static are called static nested classes.
- inner class: An inner class is a non-static nested class.
static nested class
A static nested class is a class defined inside another class using the static keyword. A Car class with a static nested Engine class where the engine details are shared and independent of a specific car object is the Real-World Example for nested class.
Static nested classes are used to logically group classes used only by the outer class, to increase encapsulation, and to save memory. Below is a code example for the static nested class.
Non-Static Nested Class (Inner Class)
A non-static nested class, commonly called an inner class, is a class defined inside another class without using the static keyword. A university class with a student inner class where each student belongs to a specific university instance for the real-world example.
Inner classes are used to logically group classes that are tightly coupled, to improve encapsulation and security, to access outer class instance variables easily, and to write cleaner and more readable code.



Comments
Post a Comment