Nested Class:
- A nested class is a class that is defined within another class.
- It can be static or non-static and can access the members of the enclosing class.
- Nested classes are mainly used to logically group classes that are only used in one place or for better encapsulation and organization of code.
Example:
class Outer {
private int outerVar;
class Inner {
void display() {
System.out.println("Inner class method, outerVar = " + outerVar);
}
}
}
Explanation:
In the example above, the Inner class is nested within the Outer class. It has access to the private member `outerVar` of the Outer class.
Sample Use:
Nested classes are commonly used in scenarios where a class is only relevant within the context of another class. For example, in GUI programming, a Button class might be nested within a Window class because it only makes sense to have buttons within a window.
Analogy:
Imagine a company (Outer class) with various departments. Each department (Inner class) has its own set of employees and resources but operates under the umbrella of the company. Similarly, nested classes operate within the scope of the enclosing class but have their own functionalities and characteristics.
Comments
Post a Comment