Table of contents
1.
Introduction
1.1.
Syntax
2.
Need of Inner Class in Java
3.
Types of Inner Class
3.1.
1. Nested Inner Classes
3.2.
Java
3.3.
2. Method Local Inner Class
3.4.
Java
3.5.
3. Static Nested Classes
3.6.
Java
3.7.
4. Anonymous Inner Class
3.8.
Java
3.9.
Java
4.
Advantages of Inner Class in Java
5.
Disadvantages of Inner Class in Java
6.
Frequently Asked Questions
6.1.
What is the difference between inner class and nested class?
6.2.
When to use an inner class?
6.3.
What is the difference between an inner class and a subclass?
6.4.
Why is an inner class static in Java?
7.
Conclusion
Last Updated: Dec 19, 2024
Easy

Inner Class in Java

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Inner classes in Java are classes defined within another class, providing better encapsulation and organization of code. They enable more logical grouping of classes that are only used in one place, improving code readability and maintainability.

Inner Class in Java

 In this article, we will explore different types of inner classes, their benefits, and how they can be effectively used in Java programming.

An inner class is a class declared inside a class or an interface. The existence of an inner class makes our code more readable and maintainable. The purpose of an inner class is to bind the group classes together that belong to the same category. To access this inner class, one must create an object of the outer class and then make an object of the inner class.

Syntax

class Java_Outer_class {
	//code
	class Java_Inner_class {
		//code 
	}
}

Need of Inner Class in Java

  • Logical Grouping of Classes: Inner classes help in grouping classes that are logically related and used only by the outer class, enhancing code organization and clarity.
     
  • Encapsulation: Inner classes can hide implementation details from other classes, providing better encapsulation and scope control within the outer class.
     
  • Improved Readability: By keeping related functionality together, inner classes make the code more readable and easier to maintain, as the relationship between the outer and inner classes is clearly defined.
     
  • Access to Outer Class Members: Inner classes can access the members, including private members, of the outer class, facilitating tighter integration between related functionalities.
     
  • Simplification of Code: In scenarios where only one instance of a class is needed in relation to another class, inner classes reduce the complexity of the overall design.

Types of Inner Class

  1. Nested Inner Classes
  2. Method Local Inner Classes
  3. Static Nested Classes
  4. Anonymous Inner Classes

1. Nested Inner Classes

This inner class helps to access any private instance of the outer class. We can access the private modifier, protected, public, and default modifier in this category. An interface can also be nested inside and have access specifiers like a class.
 

Furthermore, inner classes facilitate more better handling of event listeners and callbacks in GUI applications by maintaining related functionality within a single context. They also promote better modularization, ensuring that classes designed for specific tasks remain encapsulated within the outer class, enhancing overall code organization.

Syntax

Outer_Demo outer = new Outer_Demo();
Outer_Demo.Inner_Demo = inner = outer.new Inner_Demo();

 

Implementation

  • Java

Java

class Outer_Demo
{

private class Inner_Demo
{
public void print()
{
System.out.println("This is an inner class.");
}
}
void display_Inner()
{
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}

public class Nested_Inner
{
public static void main(String args[])
{
Outer_Demo outer = new Outer_Demo();
outer.display_Inner();
}
}
You can also try this code with Online Java Compiler
Run Code

Output

This is an inner class.

In this example, we have created two classes, one outer class, and one inner class, internal to the outer class. We have separately created two class objects called the outer and inner functions, declared inside the classes. 

Also read, Swap Function in Java

2. Method Local Inner Class

When a class has written within a method of this type, which will be local to this Method, this category of inner class is declared within a method of an outer class, and this can be accessed by creating a local object of an inner class. Like local variables, the scope of the inner class is limited within the Method. Since they can access the final or effectively final variables from the enclosing method, they enable cleaner code while maintaining the ability to leverage data specific to that method.

Syntax

class Outer {
	//code
	Class Inner{
		Inner in = new Inner();
	}
}

 

Implementation

  • Java

Java

class Outer 
{
void outerMethod()
{
System.out.println("inside outer Method");

class Inner
{
void innerMethod()
{
System.out.println("inside inner Method");
}
}

Inner inn = new Inner();

inn.innerMethod();
}
}

public class Method_Local_Inner{

public static void main(String[] args)
{
Outer out = new Outer();
out.outerMethod();
}
}
You can also try this code with Online Java Compiler
Run Code

Output

inside outer Method
inside inner Method
You can also try this code with Online Java Compiler
Run Code

In this example, we have used a method local inner class. We have simply created the object of the method local class in the same class and the outer class object in the main Method.

3. Static Nested Classes

A static inner class is a type of class that is a nested class and static member of the outer class. It can be accessed without creating the object of the outer class. It is like a static member, which does not have access to instance variables and methods of the outer class.

Syntax

class MyOuter {
	static Class Nested_Demmo {
	}
}

 

Implementation

  • Java

Java

class OuterDemo {
private static void outerMethod()
{
System.out.println("inside outer Method");
}
static class Inner {
public static void display()
{
System.out.println("inside inner class Method");
outerMethod();
}
}
}
public class Static_Nested {

// Main driver method
public static void main(String args[])
{

OuterDemo.Inner temp = new OuterDemo.Inner();
temp.display();
}
}
You can also try this code with Online Java Compiler
Run Code

Output

inside inner class Method
inside outer Method

In this example, we have created two classes and simply call the function defined in the outer class, and it will print whatever is in the function.

Also see, Java Ioexception

4. Anonymous Inner Class

When an inner class is declared without a name, it has termed the anonymous inner class. In this case of the anonymous inner class, we declare and instantiate them simultaneously. 

Syntax

AnonomousInner an_Inner = new AnonymousInner() {
	public void my_method() {
		//code
	}
};

 

Implementation 1

  • Java

Java

interface Hello {

   void show();
}
class Anonymous_Inner{

   static Hello hl = new Hello()
    {           
       public void show()
       {          
           System.out.println("I am in the anonymous class.");
       }
   }; 
   public static void main(String[] args)
   {
       hl.show();
   }
}
You can also try this code with Online Java Compiler
Run Code

Output

I am in the anonymous class.
You can also try this code with Online Java Compiler
Run Code

 

In this example, we have taken an anonymous class, we also have created the interface along with its object, then we simply called the function to print the further.

Implementation 2

  • Java

Java

import java.util.*; 
class Demo {
void show() {
System.out.println( "I am in show method of the superclass");
}
}
class Flavor1Demo {
static Demo d = new Demo() {
void show() {
super.show();
System.out.println("I am in Flavor1Demo class");
}
};
public static void main(String[] args) {
d.show();
}
}
You can also try this code with Online Java Compiler
Run Code

Output

I am in show method of the superclass
I am in Flavor1Demo class

In this example, we have used a different implementation of an anonymous inner class. Here we have created two classes. Demo one acts as a superclass, and the anonymous class acts as a subclass. We have used show methods in both classes.

You can also read about the topic of Java Destructor and Hashcode Method in Java.

Advantages of Inner Class in Java

  1. The inner class should be used by an outer class. An inner class represents the relationship that helps to access all data members and methods which includes the private class.
     
  2. The inner class helps us to develop more readable and representable code as they logically place classes and interfaces in a readable manner.
     
  3. It allows code optimization which requires us to write less code. 

Disadvantages of Inner Class in Java

  • Inner classes can make the code more complex and harder to understand, especially for those unfamiliar with the structure, as they introduce additional layers of hierarchy.
     
  • Since inner classes maintain a reference to their outer class, they may lead to increased memory consumption, especially if the outer class is long-lived while the inner class is short-lived.
     
  • Inner classes are tightly coupled with their outer class, making them less reusable in different contexts or applications compared to standalone classes.
     
  • Although inner classes can access private members of the outer class, this can lead to design issues where inner classes inadvertently create dependencies on the outer class's implementation details.
     
  • The visibility and scoping rules associated with inner classes can confuse developers, leading to potential bugs or misunderstandings in how objects are instantiated and managed.

Frequently Asked Questions

What is the difference between inner class and nested class?

The term "inner class" refers specifically to non-static classes defined within another class, while "nested class" includes both inner classes and static nested classes. Static nested classes do not have access to instance variables of the outer class, unlike inner classes.

When to use an inner class?

Use inner classes when you need to logically group classes that are only relevant to the outer class, enhance encapsulation, or simplify code that requires tight coupling between classes. They are ideal for event handling or implementing helper classes within a specific context.

What is the difference between an inner class and a subclass?

An inner class is a class defined within another class, with direct access to the outer class’s members. A subclass is a class that extends another class, inheriting its properties and methods, but not necessarily defined within it.

Why is an inner class static in Java?

An inner class is static in Java to allow it to be instantiated without an instance of the outer class. A static inner class can access only static members of the outer class, not its instance members.

Conclusion

In this blog, we covered the inner class. We briefly introduced what the inner class is, along with its syntax. We also explained the different types of inner classes and their syntaxes. We also discussed several examples of these types of inner classes.

Recommended Article

Live masterclass