Different types of inner classes in Java

What are different types of inner classes? Nested -level classes, Member classes, Local classes, Anonymous classes. Explain them.

There are 4 types of inner classes - Member inner class, Local inner class, Static inner class and Anonymous inner class

1. Member inner class – A member of a class(enclosing class).
2. Local inner class – An inner class that is defined within a block.
3. Static inner class – Like static members, this class itself is static.
4. Anonymous inner class – A class without a name and implements exactly only one interface or exactly extends one abstract class.

The enclosing class can not have the accessibility to the inner class. To do so, the outer class must create an object of its nested class except for static inner class. The member classes can access all of its enclosing class’s members, because inner class is like a member of a class.

Anonymous inner class is used when an object creation, one time single method invocation to be done and releasing the object at once. This is particular in event driven programming.

The nested classes are implemented in handling AWT, Swing and Applet programming. An anonymous inner class is invoked when an action event is to be performed.

Nested top-level classes -
The nested class is accessed the same way a package is.
Eg.: outer.inner
Top-level inner classes implicitly have access only to static variables.

Member classes -
Member inner classes are just like other member methods and variables.
A public member class behaves similar to a nested top-level class with the difference being that member classes have access to the specific instance of the enclosing class.

Local classes -
Local classes are like local variables, specific to a block of code and their scope is only within the block of their declaration.
The modifiers (public, protected, private, and static) cannot be used with them as local classes are not members.

Anonymous classes -
Anonymous classes have no name. No constructor can be provided for them.
What are packages in Java?
What are packages in Java? - Package is a collection of classes that avoids name space collision...
What are Native methods in Java?
Java Native methods - Java applications can call code written in C, C++, or assembler. This is sometimes done for performance.....
Java Reflection API - What is Reflection API in Java?
Java Reflection API - The Reflection API allows Java code to examine classes and objects at run time. The new reflection classes....
Post your comment