Nested Class in Java You Should Know About
Updated on Nov 24, 2022 | 7 min read | 5.2k views
Share:
For working professionals
For fresh graduates
More
Updated on Nov 24, 2022 | 7 min read | 5.2k views
Share:
Table of Contents
In Java, we can define a class within another class, a concept known as a nested class. Thus, a nested class in Java is a member of its enclosing (outer) class. However, unlike an outer class that can only be declared public or package-private, a nested class can be declared public, private, package-private, or protected.
Nested classes are of two types, each suitable for use in specific situations. Furthermore, nested classes bring many benefits to the table, making them a fundamental concept for anyone learning the Java programming language.
A nested class in Java is declared within another class known as the enclosing or outer class. The concept of nested classes enables the logical grouping of classes used in one place, increases encapsulation, resulting in a more maintainable and readable code.
The syntax of a nested class is illustrated below:
class OuterClass {
…
class NestedClass {
…
}
}
A nested class in Java reflects the relationship between two classes. Hence, the best use of a nested class depends on its enclosing class for its functions or makes sense only with respect to its enclosing class. Moreover, a nested class has access to the members of its enclosing class regardless of whether the latter is declared private. However, the nested class cannot access class members outside its enclosing class.
A nested class in Java can be declared static or non-static. Based on this, nested classes are of two types:
Non-static nested class or inner class is of the following three types:
Let’s understand each type of nested in a bit more detail and with examples.
A static nested class in Java is associated with its outer class. Like a static member, it is bound to the class itself rather than an instance of it. Thus, we can instantiate a static nested class without creating an intermediate instance of the outer class. Like static class methods, static nested classes cannot directly refer to instance methods or variables declared in their enclosing class, except through an object reference.
class OuterClass {
…
static class StaticNestedClass {
…
}
class InnerClass {
…
}
}
The syntax for instantiating a static nested class is as follows:
StaticNestedClass staticNestedObject = new StaticNestedClass();
A static nested class in Java behaves and follows the same rules as any other class:
Given below is a Java program example to show a static nested class:
class OuterTest{
static int num=20;
static class Inner{
void msg(){System.out.println(“The data is “+num);}
}
public static void main(String args[]){
OuterTest.Inner obj=new OuterTest.Inner();
obj.msg();
}
}
Output: The data is 20
In the above example, we have created an instance of the static nested class since it has an instance method msg(). However, we don’t need to create an object of the outer class because the nested class is static, and it is possible to access static methods, properties, or classes without an object.
A non-static nested class or inner class in Java is associated with instances of its enclosing class and can directly access that object’s instance methods and variables. Furthermore, an inner class cannot define static members itself because it is associated with an instance. It can, however, access all members of the enclosing class and not just the static members. Thus, we need an instance of its enclosing class to instantiate an inner class.
In Java, inner classes are of the following types:
A member inner class is a non-static class defined inside a class but outside a method. It can be declared with access modifiers like private, public, default, and protected.
Given below is an example program to demonstrate a member inner class:
class MemberOuter{
private int num=15;
class Inner{
void msg(){System.out.println(“The number is “+num);}
}
public static void main(String args[]){
MemberOuter obj=new MemberOuter();
MemberOuter.Inner in=obj.new Inner();
in.msg();
}
}
Output: The number is 15
In the above example, the method msg()in the member inner class is accessing the outer class’s private data members.
A local inner class in Java is a class that’s created inside a method. The local inner class is typically defined inside a block which could be a method body, an if clause, or a for loop. Thus, a local inner class is not a member of any enclosing class but belongs to the block within which they are defined. Therefore, a local inner class cannot have any access modifier associated with it. To invoke the methods of a local inner class, we need to instantiate the class inside the method.
Given below is an example program to show a local inner class:
public class LocalInner{
private int num=43; //instance variable
void display(){
class Local{
void msg(){System.out.println(num);}
}
Local loc=new Local();
loc.msg();
}
public static void main(String args[]){
LocalInner obj=new LocalInner();
obj.display();
}
}
Output: 43
An anonymous inner class in Java is an inner class with no name. Only a single object is created for such a class and is ideally used to override a class or interface method. We can create an anonymous inner class in Java either by using a class or an interface.
Example of anonymous inner class in Java using class:
abstract class Food{
abstract void eat();
}
class TestAnonymous{
public static void main(String args[]){
Food f=new Food(){
void eat(){System.out.println(“Healthy and tasty”);}
};
f.eat();
}
}
Output: Healthy and tasty
Example of anonymous inner class in Java using interface:
interface Vehicle{
void drive();
}
class TestAnnonymousInner1{
public static void main(String args[]){
Vehicle v=new Vehicle(){
public void drive(){System.out.println(“Cars and buses”);}
};
v.drive();
}
}
Output: Cars and buses
A static nested class does not have direct access to other members of the enclosing class. Being static, it can only access the non-static members of its enclosing class through an object and cannot directly refer to the non-static members. This limitation is the sole reason why static nested classes are used infrequently.
On the contrary, a non-static nested class or inner class has direct access to all members of its enclosing class and can refer to them the same way as other non-static members of the enclosing class. Thus, a non-static nested class finds more use than its static counterpart.
The following reasons will convince you why using a nested class in Java has its perks:
A nested class is a class defined within another class. The class that holds the nested class is called the enclosing class. Therefore, the scope of a nested class is limited by its enclosing class. Moreover, while a nested class can access the members of its enclosing class, the reverse is not true. A nested class can be declared private, package-private, public, or protected and is frequently used to increase encapsulation, enhance code readability, and logically group classes that find use only in one place.
If you want to learn more about Java and hone your skills to land an entry-level position in software roles, upGrad’s Job-linked PG Certification in Software Engineering is the course for you!
Here are some program highlights of the program:
Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources