Introduction

Java is known for its exemplary features and Java inner class is one of them. Although variables, methods and constructors are usual members of a class, it is also possible to have another class declared inside a primary class, which is essentially a Java inner class. The scope of an inner class is limited to the scope of its outer class. For instance, if class B is defined inside class A, then class B cannot exist as itself outside class A. Inner classes were introduced back when Java 1.1 was rolled out.

Following is the simple Syntax of a Java inner class:

1. class classA 
2. {
3. //other members of class A defined here. 
4. class classB
5.      {
6.        // members of class B defined here.
7.      }
8.  }

Java inner class is one of the most well-regarded features in Java due to its numerous advantages. Not only does it help Java developers construct a better program, but also makes it convenient for them to code in.

Following are some of the aspects under which Java inner class offers some remarkable advantages, which we will explore further in this article with examples.

The object-oriented aspect

The primary feature of the Java inner class is to allow developers objectification that normally would not be possible. It also helps them to make better use of the object-oriented aspects of Java.

For instance, let’s take a look at class B mentioned in the example before. Since an instance of Class B is a member of its parent instance of class A, it has access to every member and method in the parent class. At first glance, this might not seem like an advantage as we already have a similar type of access within a method of a parent class but now, the member class allows the developers to take the actual logic out of the parent class and make objects out of it.

From an object-oriented point of view, it maintains the encapsulation while giving the functionality where it is unreachable. This offers even more advantages like:

  • It allows direct access to all the variables and methods of the outer class, including private ones.
  • It can be used to develop more readable code.
  • It also means that developers will now have to write less code, saving time and reducing redundancy.
  • It increases the encapsulation as well.

The code organizational aspect

From an organizational point of view, inner classes allow to further organize the code structure by the use of namespaces. Without an inner class in Java, you would probably be dumping everything in a flat package like this code mentioned below as you are limited to a linear hierarchy structure:

1. Package01
2. 
3. class A
4. class B      
5. class C

As you can see, the absence of an inner class makes the code difficult to organize and manage. With an inner class, the code can be organized based on the scope of classes. If used intelligently, inner classes can provide a structural hierarchy that more naturally fits your inner and outer classes, keeping the code well organized and more readable.

1. package 01
2. 
3. class A
4. class B
5. class B1
6. class B2
7. class B3
8. class C

Callback function

A callback function is a common function in modern programming languages that is passed onto another function as an argument and is expected to execute after a particular event. Its purpose is to inform a class when a task is executed in another class.

Inner classes provide a convenient method for defining callbacks. The best example would be of a UI code as it indicates to another class when the user has executed an action. Most Java UI code has a component that calls an actionPerformed() method. The problem occurs when developers have their main window implement the ActionListener function resulting in all the components ending up sharing the same actionPerformed() method.

To find out which component it has executed, it requires a lengthy if-else or switch statements in the actionPerformed() method.

See this example of a monolithic implementation below:

1. public class GUI.101 extends JFrame implements ActionListener
2. {
3.   protected JButton btn1;
4.   protected JButton btn2;
5.   protected JButton btn3;
6.   ...
7.   public void actionPerformed(ActionEvent a)
8.   {
9.     if(a.getSource()==btn1)
10.     {
11.       // perform the respective task
12.     }
13.   else if(a.getSource()==btn2)
14.     {
15.       // perform the respective task 
16.     }
17.   else if(a.getSource()==btn3)
18.     {
19.       // perform the respective task
20.     }
21.   }
22. }

Whenever you see switches or extended if-else blocks, it is a red alert because such constructs are very bad object-oriented design implementations. After all, a minor change in one section of the code will most probably require a corresponding change in all the switch/if statements.

Java inner class allows developers to skip the switched actionPerformed() method by defining an inner class that implements ActionListener for every component respectively. It may require multiple inner classes but it gets the task done without any redundancy or lengthy conditional blocks. It not only allows to avoid large switch statements but also maintains encapsulation as a bonus.

Moreover, it can also significantly improve the performance of the code as inner classes allow to set up a 1 to 1 correspondence between the action performer and the action listener functions.

Using inner classes, the same program would look like this:

1. public class GUI.101 extends JFrame
2. {
3.   protected JButton btn1;
4.   protected JButton btn2;
5.   protected JButton btn3;
6.   class Btn1Handler implements ActionListener
7.   {
8.     public void actionPerformed(ActionEvent a)
9.     {
10.       // performs the respective task
11.    }
12.  }
13.   ...
14.   protected void GUIbuilder()
15.   {
16.     // initialize all the btns
17.     btn1 = new JButton();
18.     btn2 = new JButton();
19.     Btn3 = new JButton();
20.     ...
21.     // register an inner class action listener instance for each button
22.
23.     btn1.addActionListener(new Btn1Handler());
24.     // now same line of code will be repeated for each btn 
25.    }
26. }

Security aspect

Java inner class is also very useful for providing security for an important piece of code. For instance, if an inner class is declared as private, it is unavailable to other classes which means that an object of the inner class cannot be created in any other classes.

Let’s say, we create a class called ‘’Students.’’ To get some students’ details, we define instance variables ‘Marks’ and ‘Grade’ in the class. calcGrade() method calculates the grade and then it will display the marks. Initially, it would be under default access modifiers so any developer can easily create an object of this class and access its members from the outside. For example, any programmer can create an instance of a Student class and can change the criteria of grading which could affect the whole application.

It is certain that methods like calcGrade() are very sensitive and must be protected. To cater to that you can write the calcGrade() method in an inner class and make it private, which means no one will be able to access it. But how will an authorized person be able to access that inner class then? For that, first, a contact() method is to be created inside the outer class. An object of the inner class will be then created inside the contact method to access the members of it. Whenever the contact() method will be called, authentication will be required, resulting in a proper safe mechanism for accessing important or sensitive methods in java.

See Also: HashMap Implementation in Java

Wrapping it up

The above-mentioned are some of the advantages of the Java inner class. Being a Java enthusiast yourself, you will further be able to explore what features and benefits you are looking for once you use the Java inner class feature. Whether it is for easy maintenance of code, improved readability, better encapsulation, writing fewer lines of code or for better security, Java inner class covers it all. It is not surprising that it is one of the oldest features offered by Java and it is still used to a great extent by new as well as experienced Java developers.

Author

Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design. He writes and teaches extensively on themes current in the world of web and app development, especially in Java technology.

Write A Comment