Java Inner Class and its 4 Types You Must Know About!

We have already discussed classes in our previous article on Java Classes. In Java, it is possible to nest the classes that is, writing classes inside classes. Such type of structure is also known as nested classes or inner classes. In today’s article, we are going to discuss the same in detail about Java Inner Class, along with their types that are explained with the help of syntax and coding examples.

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

Java Inner Class

A class within another class is called a nested class or an inner class. In other words, the inner class is a member of a class just as a class has a member as variables and methods; it can also have another class as its member. Such class, which has other classes as its members is called a top-level class or outer class. A top-level class may contain any number of inner classes.

Need for Inner Class in Java

Now, you might be thinking about why to use an inner class rather than using separate classes? The following points will help you understand the purpose of using inner class along with its importance:

  • It helps in the logical grouping of classes that belong together:

Suppose there is a class that is useful only to a single class, then we can logically embed it in that class and keep the two classes together. It will help their package to be more streamlined.

  • It helps to increase the encapsulation:

Suppose there are two top-level or outer classes, named C1 and C2, where class C2 needs to access the private members of the class C1. By nesting class C2 within the class C1, members of C1 can be declared as private, and C2 can access them. Also, we can protect C2 from the outside world. Eventually, this will lead to strong encapsulation and security.

  • It helps to increase the readability and maintainability of the code:

Placing inner classes within the top-level classes helps to put the code closer to where it is going to be used.

Syntax of writing inner class:

Following is the syntax to write an inner class or nested class. Here, the class OuterClassDemo is the outer class or the top-level class and the class InnerClassDemo is the nested or inner class.

class OuterClassDemo
{
    //code of the outer class

    class InnerClassDemo
    {
        //code of inner class
    }
}

Types of Inner Classes in Java

There are four types of inner classes:

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

We will discuss each of them in detail along with their syntax and code:

1. Nested Inner Class

Nested Inner class is an inner class that can access other instance variables of the outer class, even if they are declared as private. We can use any access modifier for the nested inner class – public, private, protected, or default.

It’s the right time to take a deep dive into the concept of Access Modifiers in Java you didn’t know about.

Code to understand Nested Inner Class:

package com.techvidvan.innerclass;
public class JavaOuterClass
{
  // private variable of the outer class
  private int value = 30;

  // inner class
  class JavaInnerClass
  {
    // public variable of the inner class
    public int getValue()
    {
      System.out.println("This is the getValue method of the inner class:");
      return value;
    }
  } //inner class end here

  public static void main(String args[])
  {
    //Creating object of outer class
    JavaOuterClass outer = new JavaOuterClass();

    // Creating object of inner class
    JavaOuterClass.JavaInnerClass inner = outer.new JavaInnerClass();
    System.out.println("Value:" inner.getValue());
  }
}

Output:

This is the getValue method of the inner class:
Value: 30

2. Method Local Inner class

Method Local Inner Class allows us to declare a class inside a method body that will be of a local type. The scope of the inner class is restricted within the method, similar to the local variables. We can initialize a local inner class only inside the method where the inner class is defined. We can not declare Method Local Class as private, protected, static and transient but we can declare it as abstract and final, but not both at the same time.

Code to understand Method Local Inner Class:

package com.techvidvan.innerclass;
//outer class
public class OuterClass
{
  void outerMethod()
  {
    System.out.println("Inside outer method");
    //inner class inside a method of outer class
    class InnerClass
    {
      void innerMethod()
      {
        System.out.println("Inside inner method");
      }
    } //inner class ends here

    //initializing object of inner class inside the method
    InnerClass innerObj = new InnerClass();
    innerObj.innerMethod();
  } //method ends here

  public static void main(String[] args)
  {
    OuterClass outerObj = new OuterClass();
    outerObj.outerMethod();
  }
}

Output:

Inside outer method
Inside inner method

Note: A Method Local class cannot access a local variable from the outer class. To access the local variable from the outer class, we must define it as final.

For example, the below code generates an error if we do not declare the variable as final:

package com.techvidvan.innerclass;
//outer class
public class OuterClass
{
  void outerMethod()
  {
    final int var = 60; //declaring variable as final
    System.out.println("Inside outer method");
    //inner class inside a method of outer class
    class InnerClass
    {
      void innerMethod()
      {
        System.out.println("\nInside inner method");
        System.out.println("Value of variable is: "+var);
      }
    }//inner class ends here

    //initializing object of inner class inside the method
    InnerClass innerObj = new InnerClass();
    innerObj.innerMethod();
  } //method ends here
  public static void main(String[] args)
  {
    OuterClass outerObj = new OuterClass();
    outerObj.outerMethod();
  }
}

Output:

Inside outer method
Inside inner method
Value of variable is: 60

3. Static Inner class

A static inner class acts as a static member of an outer class. As it is a static member, we can access it without initializing the outer class with the help of a static method. So, we can say that technically Static Inner classes are not a Java inner class. Similar to static members, a static nested class cannot access the instance variables and methods of the outer class.

Code to understand Static Inner Class:

package com.techvidvan.innerclass;
public class OuterClassDemo
{
  static class NestedDemo
  {
    public void myMethod()
    {
      System.out.println("This is a static nested class");
    }
    public static void main(String args[])
    {
      //Accessing the static nested class without initializing the object //of Outer class
      OuterClassDemo.NestedDemo nested = new 					 
                        OuterClassDemo.NestedDemo();
                         nested.myMethod();
    }
  }
}

Output:

This is a static nested class

4. Anonymous Inner class

Anonymous inner class is an inner class that is declared without a name. It helps you to make a more concise code. Generally, they are used when there is a need to override the method of a class or an interface. We can also use them if we need to use a local class only once. They are similar to local inner classes with the exception that they do not have a name.

Code to understand Static Inner Class:

package com.techvidvan.innerclass;
interface AnonymousAnimal
{
  void type();
}
public class AnonymousInnerClass
{
  public static void main(String args[])
  {
    AnonymousAnimal animal = new AnonymousAnimal(){
      public void type()
      {
        System.out.println("Anonymous Anteater");
        System.out.println("Anonymous Unicorn");
        System.out.println("Anonymous Capybara");
        System.out.println("Anonymous Beaver");
      }
    };
    animal.type();
  }
}

Output:

Anonymous Anteater
Anonymous Unicorn
Anonymous Capybara
Anonymous Beaver

Summary

Inner classes are the classes inside classes that behave differently from the subclasses. Coming to the end of our Java Tutorial, we have learned about the Inner classes and the importance of using inner classes. Also, we have covered each type of inner class along with the example. This article will surely help you to understand the concept of Inner classes in Java in an easy way.

Thank you for reading our article. If you have any queries do tell us through the comment box below.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.