Programs

Nested Class in Java You Should Know About

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.

What is a Nested Class in Java?

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.

Types of Nested Class in Java

A nested class in Java can be declared static or non-static. Based on this, nested classes are of two types:

  • Static nested class
  • Non-static nested class or inner class

Non-static nested class or inner class is of the following three types:

  • Member inner class
  • Local inner class
  • Anonymous inner class

Let’s understand each type of nested in a bit more detail and with examples.

Static Nested Class in Java

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:

  • Supports all access modifiers
  • Allows defining both static and non-static members
  • Cannot access non-static members of its outer class
  • Can access static members (including private) of its outer 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.

Non-Static Nested Class in Java

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:

Member inner class

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.

Local inner class

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

Anonymous inner class

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

 

How Is a Static and Non-Static Nested Class Different?

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.

Why Use a Nested Class in Java?

 

The following reasons will convince you why using a nested class in Java has its perks:

  • It makes the code more readable and maintainable. Nesting a small class within a top-level class places the code closer to where it is used.
  • It logically groups classes that are used only in one place. Nesting two classes and keeping them together is especially useful when a class makes sense in the context of only one other class.
  • It enhances encapsulation. Suppose there are two top-level classes X and Y, where Y needs access to X’s members that would otherwise be declared private. Y can access X’s members even if they are declared private by nesting class Y within class X. Moreover, Y remains hidden from the outside world.

Summary

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:

  • 500+ hours of online training with live sessions and industry projects
  • Specialisation in MERN/Cloud-Native
  • Comprehensive learning support
  • Q&A forums with peers and industry experts
  • Networking with industry experts

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.

Why use nested classes?

There are several reasons for using Java nested classes. They enhance the code’s readability and maintainability, increase encapsulation, and logically group classes used in only one place.

What are the four types of nested classes?

Overall, nested classes are of two types: static and non-static. Non-static nested classes or inner classes are further of three types: local inner class, anonymous inner class, and member inner class.

What is the difference between inner class and nested class

In Java programming, a nested class is a class created within another class. Contrarily, an inner class is a non-static type of nested class and differs from a static one.

Want to share this article?

Plan your Software Development Career Now.

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

×
Let’s do it!
No, thanks.