Use Of Inner Class In Java
Posted By Vakeel Malik | 26-May-2018
Introduction: Inner class is a class written within another class. An inner class is a basically a safety mechanism since it is hidden from another class in its outer class.
To make the instance variables not available outside the class. we use private access specifier before the variables. this is how we provide the security mechanism to a variable. similarly, in some cases, we want to provide the security for the entire class. In this case, can we use private access specifier before the class? the problem is if we use private access specifier before a class is not available to the Java compiler or JVM. So it is illegal to use 'private' before a class name in Java.
but the private specifier is allowed to before an inner class and thus it is useful to provide security for the entire inner class. Once private is used before the inner class, it is not available to other class. this means an object to inner class cannot be created in any other class.
Now, see the complete program to create an inner class Calculation in the outer class Bank. Also in this program, we are showing that a user can use inner class by calling the applyInterest() method of the outer class, where authentication is checked. thus, the outer class is acting like a firewall (implementor of security mechanism) between the user and the inner class.
There is some point about inner class.
1. An inner class is a class that is defined inside another class.
2. The object to inner class cannot be created in other classes.
3. The object to inner class can be created only in its outer class.
4. An inner class object and its outer class object are created in separate memory locations.
5. An inner class can access the members of its outer class directly.
6. An inner class in a safety mechanism.
this is a practical example of an inner class.