Note:Nested classes, also known as inner classes, are classes defined within the scope of another class. They are a feature found in many object-oriented programming languages like Java, C++, and Python. Nested classes can be useful for organizing and encapsulating code, improving code readability, and reducing namespace pollution. Here’s an overview of nested classes:
Overview
- Types of Nested Classes
- What are Nested Classes?
- Inner Class
- Local Inner Class
- Anonymous Inner Class
- Static Nested Class
What Are Nested Classes
- A class defined within a class or interface is known as a nested class.
- E.g. class Java_Outer_class{
Types of Nested Classes
- Non static nested class
- Member Inner Class
- Local Inner Class
- Anonymous Inner Class
- Static Nested Class
- Why we need these?
- Better encapsulation
- Better modularity of code
- Each inner class can extend from its own parent class, irrespective of outer class extending it.
Member Inner Class
- A non-static class that is created inside a class but outside a method is called member inner class.
Syntax:-
class Outer{
//code
class Inner{
//code
}
}
Anonymous Inner Class
- A class that have no name is known as anonymous inner class in java. It should be used if you have to override method of class or interface.
E.g.:-
abstract Class Sample
{
abstract method();
}
class Outer
{
void test()
{
Sample n = new Sample()
{
void method()
{
System.out.print(“hello”);
};
n.method();
}
Local Inner Classes
- Local classes are the ones that are defined inside a method or a scope block.
E.g.:-
class Outer{ void test(){
class localClass{
}
localClass inner = new localClass();
}
}
Static Nested Classes
- A static class created inside a class is called static nested class in java. It cannot access non-static data members and methods. It can be accessed by outer class name.
E.g.:-
class Outer{
static class inner{
}
}