Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconWhat is Inner Class in Java?

What is Inner Class in Java?

Last updated:
29th Apr, 2022
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
What is Inner Class in Java?

The concept of inner class in Java is fundamental to Java programming. In Java, a nested class and inner class are two very similar yet slightly distinct ideas of class designing and often go hand-in-hand.

A nested class is defined within another class and has two types – static nested class and non-static nested class. On the other hand, an inner class is a type of non-static nested class and is further of three types – member inner class, anonymous inner class, and local inner class.  

Check out our free courses to get an edge over the competition.

So, what do these three types of inner classes mean, and what is their use? Read on to find out in this detailed guide on Java inner class.

Ads of upGrad blog

Meaning of Inner Class in Java

A non-static nested class or inner class is defined within another class and has access to members of the outer class (enclosing class). On the contrary, a static nested class is also a class defined within another class, but unlike a non-static nested class, it cannot access the member variables of its outer class. In the case of a non-static nested class, we are not required to create an instance of the outer class. But in the case of an inner class, we must first instantiate the outer class to be able to instantiate the inner class.

Source

Learn Online software development courses from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Types of Inner Class in Java 

In Java, inner classes are of the following three types:

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

Check out upGrad’s Advanced Certification in DevOps

Now, let us understand each type of inner class with examples. 

1. Member Inner Class

A member inner class in Java is a non-static nested class created inside a class but outside a method. Also referred to as a regular inner class, a member inner class can be declared with access modifiers like private, public, default, and protected.

The syntax for a member inner class is as follows:

class Outer{  

 //code  

 class Inner{  

  //code  

 }  

}  

Member inner class in Java example:

Given below is a program to demonstrate how to create an inner class and access it. We will make the inner class private and use the method display_Inner()to access the class. 

class DemoOuter {

   int num;

 // inner class

   private class DemoInner {

      public void print() {

         System.out.println(“This is the inner class”);

      }

   }

Check out upGrad’s Full Stack Development Bootcamp (JS/MERN) 

   // Accessing the inner class from the method within

   void display_Inner() {

      DemoInner inner = new DemoInner();

      inner.print();

   }

}

   public class MyClass {

   public static void main(String args[]) {

      // Instantiating the outer class 

      DemoOuter outer = new DemoOuter();

      

      // Accessing the display_Inner() method

      outer.display_Inner();

   }

}

Output: This is the inner class

In the above example, OuterDemo is the outer class, InnerDemo is the inner class, we are instantiating the inner class inside the method display_Inner(), which is invoked from the main method.

Explore Our Software Development Free Courses

2. Anonymous Inner Class

An anonymous inner class in Java is an inner class declared without any class name and for which only a single object is created. Anonymous inner classes in Java are declared and instantiated at the same time. They are most valuable when we want to override the method of a class or interface. 

The syntax for an anonymous inner class in Java is as follows:

AnonymousInner an_inner = new AnonymousInner() {

   public void my_method() {

      

   //code

   }   

};

 An anonymous inner class in Java can be created in two ways:

  1. Using class
  2. Using interface

Anonymous inner class in Java example (using class):

abstract class Meal{  

  abstract void eat();  

}  

class TestAnonymousInner{  

 public static void main(String args[]){  

  Meal m=new Meal(){  

  void eat(){System.out.println(“Bon appetit!”);}  

  };  

  m.eat();  

 }  

}  

Output: Bon appetit!

Anonymous inner class in Java example (using interface):

interface Game{  

 void play();  

}  

class TestAnnonymousInner1{  

 public static void main(String args[]){  

 Game g=new Game(){  

  public void play(){System.out.println(“Outdoor games”);}  

 };  

 g.play();  

 }  

}  

Output: Outdoor games

Explore our Popular Software Engineering Courses

3. Local Inner Class

A local inner class in Java is a class created inside a method. As in the case of local variables, the scope of the local inner class remains restricted within the method. 

Local inner classes are defined inside a block: a method body, an if clause, or a for loop. A local inner class is not a member of any enclosing class, but instead, it belongs to the block within which it is defined. Thus, even though a local inner class in Java cannot have any access modifiers associated with it, you can mark it abstract or final. If we want to invoke the methods of a local inner class, we have to instantiate the class inside the method.

Local inner class in Java example:

Below is an example program to demonstrate how to instantiate the object of a local inner class declared inside the method of an outer class.

package innerClass; 

public class Outer_Class 

// An instance method of class Outer_Class. 

   public void display()

  { 

// Declaration of a method local inner class. 

    class Inner_Class 

    { 

       public void msg(){ 

        System.out.println(“This is a local inner class!”); 

       } 

     } 

// Create an instance of a method local inner class and call the msg() method using object reference variable i. 

     Inner_Class i = new Inner_Class(); 

       i.msg(); 

  } 

public static void main(String[] args) 

// Create an object of the outer class Outer_Class. 

     Outer_Class o = new Outer_Class(); 

       o.display(); 

   } 

}

Output: This is a local inner class!

With the fundamentals of Java inner class in mind, let us understand why we need them in the first place.

In-Demand Software Development Skills

Advantages of Java Inner Class

An inner class in Java brings three significant utilities to the table. These are as follows:

1. Since a Java inner class can access the data members and methods of the outer/main class, including private, it represents a specific type of relationship.

2. A Java inner class significantly reduces coding since it requires less to write.

3. An inner class in Java logically groups classes and interfaces in a single place, thereby enhancing the readability of the code and making it easier to maintain.

Summing Up

The concept of nested classes simplifies and adds flexibility to creating classes anywhere in Java programming. In this regard, a non-static nested class known as inner class is particularly useful, as we have already seen in our discussion so far. 

We would like to wrap up by stating two instances where the use of inner class seems most appropriate. First, a Java inner class is ideal when two classes have a close relationship and are not accessible by any other class. And second, inner classes are commonplace in Java GUI programming event handling. Therefore, Java inner classes can be safely used where listeners and their GUI components are involved.

Read our Popular Articles related to Software Development

Wondering where to learn Java?

upGrad’s Job-linked PG Certification in Software Engineering is what you’re looking for!

Ads of upGrad blog

Specially designed for fresh graduates and final years, upGrad’s Job-linked PG Certification in Software Engineering is perfect for those who want to learn to program and get placed in entry-level software roles. This 5-month online program will teach top software skills like Java, JavaScript, HTML5, DSA, AWS, MERN, and more!

Program Highlights:

  • Specialisation in MERN Stack/Cloud-Native
  • 500+ hours of online learning
  • 350+ hours of hands-on training
  • 50+ live sessions
  • Five industry projects
  • Networking with industry experts
  • Q&A forums with peers and industry experts
  • Learning support from teaching assistants and industry mentors

Sign up today to learn from the best in the industry!

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)

1What is the difference between inner class and subclass?

An inner class is a class that is nested or defined within another class. On the other hand, a subclass is a class that is derived from another class. Moreover, while an inner class can only be accessed by using the reference of the outer class within which it is nested, a subclass can be accessed directly unless the subclass has inherited private variables.

2Can we write class inside a class in Java?

Yes, we can define a class within another class in Java. Such a class is known as a nested class, and it allows us to logically organise classes in one place, thereby creating a more maintainable and readable code. As part of its enclosing class, a nested class can be declared public, private, package-private, or protected.

3Can Java inner class be private?

Yes, a Java inner class can be private. But once an inner class is declared private, it cannot be accessed from an object that’s outside the class. Inner and outer classes have access to each other’s private instance variables and private methods. As long as we are within the outer or inner class, the modifiers private and public have the same effect.

Explore Free Courses

Suggested Blogs

Marquee Tag & Attributes in HTML: Features, Uses, Examples
5031
In my journey as a web developer, one HTML element that has consistently sparked both curiosity and creativity is the venerable Marquee tag. As I delv
Read More

by venkatesh Rajanala

29 Feb 2024

What is Coding? Uses of Coding for Software Engineer in 2024
5011
Introduction  The word “coding” has moved beyond its technical definition in today’s digital age and is now considered an essential ability in
Read More

by Harish K

29 Feb 2024

Functions of Operating System: Features, Uses, Types
5016
The operating system (OS) stands as a crucial component that facilitates the interaction between software and hardware in computer systems. It serves
Read More

by Geetika Mathur

29 Feb 2024

What is Information Technology? Definition and Examples
5008
Information technology includes every digital action that happens within an organization. Everything from running software on your system and organizi
Read More

by spandita hati

29 Feb 2024

50 Networking Interview Questions & Answers (Freshers & Experienced)
5056
In the vast landscape of technology, computer networks serve as the vital infrastructure that underpins modern connectivity.  Understanding the core p
Read More

by Harish K

29 Feb 2024

10 Best Software Engineering Colleges (India and Global) 2024
5205
Software Engineering is developing, designing, examining, and preserving software. It is a structured and trained approach through which you can devel
Read More

by venkatesh Rajanala

28 Feb 2024

What is Composition in Java With Examples
66343
Java is a versatile language that supports object-oriented programming and code reusability with building relationships between two classes. There are
Read More

by Arjun Mathur

19 Feb 2024

Software Engineer / Developer Salary in India in 2024 [For Freshers & Experienced]
908058
Summary: In this article, you will learn about Software Engineer Salary in India based on Location, Skills, Experience, country and more. Today softw
Read More

by Rohan Vats

Top 40 Most Common CSS Interview Questions and Answers [For Freshers & Experienced]
15449
Every industry has started the use of websites and applications to catch up with the pace of the rapidly transforming world. CSS is one of the most cr
Read More

by Rohan Vats

19 Feb 2024

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