Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconNested Class in Java You Should Know About

Nested Class in Java You Should Know About

Last updated:
5th Nov, 2021
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
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:

Ads of upGrad blog

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.

Ads of upGrad blog

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.

Profile

Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.

Frequently Asked Questions (FAQs)

1Why 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.

2What 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.

3What 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.

Explore Free Courses

Suggested Tutorials

View All

Suggested Blogs

Top 14 Technical Courses to Get a Job in IT Field in India [2024]
90952
In this Article, you will learn about top 14 technical courses to get a job in IT. Software Development Data Science Machine Learning Blockchain Mana
Read More

by upGrad

15 Jul 2024

25 Best Django Project Ideas & Topics For Beginners [2024]
143863
What is a Django Project? Django projects with source code are a collection of configurations and files that help with the development of website app
Read More

by Kechit Goyal

11 Jul 2024

Must Read 50 OOPs Interview Questions & Answers For Freshers & Experienced [2024]
124781
Attending a programming interview and wondering what are all the OOP interview questions and discussions you will go through? Before attending an inte
Read More

by Rohan Vats

04 Jul 2024

Understanding Exception Hierarchy in Java Explained
16879
The term ‘Exception’ is short for “exceptional event.” In Java, an Exception is essentially an event that occurs during the ex
Read More

by Pavan Vadapalli

04 Jul 2024

33 Best Computer Science Project Ideas & Topics For Beginners [Latest 2024]
198249
Summary: In this article, you will learn 33 Interesting Computer Science Project Ideas & Topics For Beginners (2024). Best Computer Science Proje
Read More

by Pavan Vadapalli

03 Jul 2024

Loose Coupling vs Tight Coupling in Java: Difference Between Loose Coupling & Tight Coupling
65177
In this article, I aim to provide a profound understanding of coupling in Java, shedding light on its various types through real-world examples, inclu
Read More

by Rohan Vats

02 Jul 2024

Top 58 Coding Interview Questions & Answers 2024 [For Freshers & Experienced]
44555
In coding interviews, a solid understanding of fundamental data structures like arrays, binary trees, hash tables, and linked lists is crucial. Combin
Read More

by Sriram

26 Jun 2024

Top 10 Features & Characteristics of Cloud Computing in 2024
16289
Cloud computing has become very popular these days. Businesses are expanding worldwide as they heavily rely on data. Cloud computing is the only solut
Read More

by Pavan Vadapalli

24 Jun 2024

Top 10 Interesting Engineering Projects Ideas & Topics in 2024
43094
Greetings, fellow engineers! As someone deeply immersed in the world of innovation and problem-solving, I’m excited to share some captivating en
Read More

by Rohit Sharma

13 Jun 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon