When we declare a class inside other class or interface , is known as inner class. Inner class is used to archive encapsulation.
This special relationship gives inner class access to member of outer class as if they are the part of outer class.The inner class is a valuable feature because it allows you to group classes that logically belong together and to control the visibility of one within the other.
Inner classes, also called Nested Classes, if we define a static inner class inside outer class or top level class.
Different types of inner classes:-
There are two main types of inner classes -
a) Static member class
b) Inner class 1. Member class 2. Anonymous class 3. Local class
Static Inner Class
Features of Static Inner Class.. 1. Static inner class can access only static members of outer class. 2. Static inner class can not access not static members of outer class. 3. A static inner class is just like any other inner class, but it does not have the reference to its outer class object that generated it.
Example Code :
1. No inner class objects are automatically instantiated with an outer class object. 2. The outer class can call even the private methods of the inner class. 3. If the inner class is static, then static inner class can be instantiated without an outer class instance, otherwise, the inner class object must be associated with an instance of the outer class.
4. Inner class code has free access to all elements of the outer class object that contains it, by name (no matter what the access level of the elements is), if the inner class has a varible with same name then the outer class's variable can be accessed like this:
OuterClassName.this.variableName 5. The outer class can call even the private methods of the inner class.
Example Code :