Inner Class in Java | Use, Types, Example

Inner Class in Java | So far, we have known the members of the class are variables, methods, constructors, and initializer blocks.

But it is also possible to have a class or an interface as a member of a class.

A class declared inside another class is known as nested classes in java. The scope of a nested class is tied by the scope of its enclosing class (outer class).

Thus, if class B is defined inside class A, then class B cannot exist independently without class A. Here, class A is outer or enclosing class and class B is nested class.

A nested class in java has access to the members ( including private members) of its enclosing class. But, the enclosing class does not have access to the members of the nested class.

The class which is a member of another class can be either static or non-static. In other words, there are two types of nested classes in java: static and non-static.

The member class which is declared with a static modifier is known as static nested class in java.

The member class which is non-static is known as inner class or non-static nested class. It is the most important type of nested class.

In this tutorial, we will learn only inner class in Java. Later on, we will discuss static nested class in the further tutorial.
Inner class in Java with realtime example

Inner class in Java


An inner class in java is a class that is declared inside of another class without static modifier. It is also commonly known as a non-static nested class in Java. It can access all members (variables and methods) of its outer class.

An inner class cannot have any kind of static members. The members of the java inner class may be:

  1. Instance variables
  2. Instance methods
  3. Constructors
  4. Initializer block
  5. Inner class

Syntax of Inner class

access modifier class OuterClassName {
     . . . . . . . . . .
  access modifier class InnerClassName  {
     // Members of the inner class.
   }
  // Other members of the outer class.
}
For example:
public class Test { //  Here, Test is an outer class.
  . . . . . .
 // Inner class
  public class A { // A is inner class as a member of its outer class.
    . . . . 
  } 
}

The class that holds the inner class is called enclosing or outer class. The enclosing class is a top-level class whereas the inner class is member of outer class.

The relationship between outer class and inner class represents Has-A relationship. A Has-A relationship establishes the relationship between two classes. It is also known as composition or aggregation in Java.

When an inner class is an enclosing class for another inner class, it is called nesting of inner classes. There is no limit to the nesting of inner classes.

In which version Inner class was introduced in Java?


Inner class was introduced in the Java 1.1 version without any changes in the JVM used to handle the class files. It is completely implemented with the help of Java compiler.

Java compiler generates a separate dot class file for each inner class named Outer$Inner.class and for an outer class named Outer.class. For example, an inner class A is compiled into a class Test named Test$A.class.

If any dot class file name contains “$” symbol in its middle, it shows an inner class file. The format of the class files for inner classes has the same as class files for the outer classes.

Therefore, JVM treats the class files for inner classes and the outer classes the same.

Features of Inner class


There are several important features of an inner class that is as follows:

1. An inner class can have the same name as the outer class.

2. The scope of inner class is bounded by the scope of its outer class.

3. Without existing an outer class object or instance, there will be no chance of an existing inner class object.


4. An inner class can directly access all the variables and methods of the outer class including private.

5. Since the inner class is a regular member of the outer class just like declared variables and methods in the class.

That’s why, we can apply all java access modifiers such as public, default, protected, and private to inner class similar to the other members of a class. But the outer or normal class cannot be private or protected.

6. If the variable name of inner class is the same as the variable name of outer class, we can access the outer class variable like this. OuterClassName.this.VariableName; here this represents current outer class object.

7. Java inner class is hidden from another class in its enclosing class. Therefore, it provides a safety mechanism in the application program and decreases readability (understanding) of the program.

8. An object of inner class is often created in its outer class and cannot be created from other classes.

9. Both outer class and inner class objects are created in separate memory locations.

Syntax to create object of Inner class in Java


An instance of an inner class shares a relationship with an instance of an outer class. This relationship is such that we cannot create an instance of the inner class without having an instance of the outer class.

Therefore, to create an object of inner class, you must first have to create an object of outer class to tie to the inner class. We can create multiple objects of an inner class for the same instance of an outer class.

The syntax to create an object for the inner class is as follows:

Syntax:
  OuterClass.InnerClass innerObject = outerObject.new InnerClass();
For example:
// First create an object of Outer class Test.
   Test t = new Test();
// Second create an object of inner class A.
   Test.A innerObj = t.new A();

Let’s understand how an instance of an inner class shares a relationship with an instance of an outer class with realtime examples.

Realtime Example of Inner class


1. Suppose there is a university. University contains several departments such as electronics, computer science, electrical, mechanical, etc.

Assume that tomorrow, the government decided to close this university due to its illegal activity happening in the university. If the university is closed, all departments of this university will be closed automatically.

That’s why we can say that departments are tied to its university. i.e. their functionalities are tied with its university. So, without an existing university object, there is no chance of existing department objects.

Since the department is always a part of the university class. Hence, we must declare the department class inside the university class.

class University {  // University is outer class.
   . . . . . . .
 class Department { // Department is inner class.
    . . . . . . . . 
  }
}

Thus, without an existing one type of object, if there is no chance of existing another type of object, we should implement inner class.

2. Assume that there is a car. Within a car, there are several important individual components that are required. The most important component of the car is the engine.

The engine must be required to make a car. But without an existing car object, there is also no chance of existing an engine object.

Since an engine is always an important part of a car. Hence, the class engine must be declared inside the class car.

class Car {
  . . . . . . . . .
  class Engine  {
      . . . . . . . . . . 
  }
}

The above two realtime examples are explained to get the basic ideas of inner class. Now we will take the next example based on Java API.

3. As we know that in Java there is a Map concept in the collections API. A map is nothing but a group of key-value pairs. Each key-value pairs is called one entry. Now without an existing map object, Is there any chance of existing entry object?

The answer is no because without existing an object of a map, the entry object cannot also exist. That’s why interface entry is defined inside the map interface.

Interface Map  {  // Map is an outer interface.
  . . . . . . . . . 
  Interface Entry  { // Entry is an inner interface.
    . . . . . . . . . .  
   }
 }

Now you would have understood from the above real-time example that when should use an inner class in Java programming.

Use of Inner class in Java


There are the following important uses of inner class in Java.

1. The inner class is a valuable feature because it allows us to group classes and interfaces in one place that logically belongs together.

2. It helps to control the visibility of one within the other so that it can be more readable and maintainable.

3. The best use of java inner class is when its functionality is tied to its outer class. That is,  without an existing outer class object, there is no chance of existing inner class object. Understand the real-time examples.

4. . Java inner class is useful to provide security for the important code. For example, if we declare inner class as private, it is not available to other classes. This means that an object to inner class cannot be created in any other classes.

Let’s understand it with help of realtime example program.

Assume that we create a class BankAcct. To get some bank account details, we define instance variables ‘balance’ and ‘rate’ of interest in the class.

calInterest() method calculates the interest amount and will display balance amount. Look at the following source code.

class BankAcct {
 // Balance and Rate of interest.  
     private double bal;
     private double rate;
     
// Calculating interest and updated balance.
   void calInterest() {
      double interest = bal * rate/100;
      bal += interest;
      System.out.println("Balance amount = " +bal);
   }
}

As you observe that there is no security for this code because of not using any access modifiers before BankAcct class.

Since it is under default access modifiers, any programmer can easily create an object of this class and access the members of the class from outside other classes. Hence, there is no security for BankAcct class.

For example, any programmer can create another class. He will create an instance of BankAcct class and can change rate of interest like this:

class Myclass {
 public static void main(String[ ] args ){
 BankAcct ba = new BankAcct();
     ba.calInterest(11.5);
  } 
}

Thus, calInterest() method is very sensitive. It must be protected from outsiders because the balance accounts can be updated from outside by any other person. Only authorized person should be able to update the balance accounts.

To provide security to calInterest() method and rate of interest, if we put code of calInterest() method inside an inner class and make it private, nobody can access them from outside class. Look at the code.

class BankAcct {
   . . . . . . . . 
 private class Interest {
  private double rate;
  void calInterest() {
    double interest = bal * rate/100;
    bal += interest;
    System.out.println("Balance = " +bal);
   }
  }}

Now the question is how to access inner class?

To access inner class, we will create a contact() method inside the outer class. Inside contact() method, we will create an object of inner class and can access members of it.

An authentication bank person can interact with inner class by calling contact() method. When contact() method will be called, he will be verified with password and then he will be able to use the inner class and access it.

Thus, an inner class can provide a safety mechanism to important code in Java.

Types of Inner class in Java


Based on declaration and behaviors, there are basically four types of inner classes in Java. They are as follows:

1. Normal or Regular inner class: A class created inside another class and outside the method without static modifier is called regular or normal inner class.

2. Method local inner class: A class declared within a method of the outer class is called method local inner class.

3. Anonymous inner class: A class declared without any name at all is called anonymous inner class.

4. Static nested inner class: A class declared with static modifier within a class is called static nested inner class. It is also known as a top-level nested class. It can access only the static members of the outer class.

Note: The regular, method-local, and anonymous inner classes are non-static nested classes.

Advantages of  Inner class


There are basically five advantages of inner class in java. They are as follows:

1. Inner class provides a way to group the classes and interfaces in one place that logically belongs together.
2. It can directly access all the variables and methods of the outer class including private.
3. It is used to develop more readable and maintainable code.
4. It needs less code to write.
5. It increases encapsulation.

Difference between Nested class and Inner class in Java


Nested class is a class that is defined inside another class. There are two types of nested class: static and non-static. Non-static nested class is the inner class.


Hope that this tutorial has covered all the important features of inner class in java with realtime example programs. I hope that you will have understood the basic idea of using inner class in Java.
Thanks for reading!!!Next ⇒ Member inner class in Java

⇐ Prev Next ⇒

Leave a Comment