Thursday, August 20, 2009

Anonymous Inner Class in Java

Hi everybody, Java Code Online is going to discuss the Anonymous Inner Class in Java today. This class as the name specifies is not named. It means that this class has a body but no name. And so it is anonymous.

It is one of the most bizarre type of Inner class. It is always invoked from outside the Outer class. When the invocation is done, then this class is placed after the brackets of the method invocation. The key to understand this is that, actually the Anonymous inner class always extend or implement, but not both at the same time.

When the Outer class is invoked, then the syntax is something like:-

OuterClass oc = new OuterClass();

But when the anonymous inner class comes into picture the code is something like:-

OuterClass oc = new OuterClass(){
//some inherited method
};

The syntax though very much strange is the correct one. Here the curly braces after the instantiation call infact causes an anonymous inner class to be formed which either inherits or implements the method of the instantiated class. So the only methods available here are the one by inheritance or implements. Note the semicolon at the end of the curly braces, strange but true. Here the main concept is of Polymorphism as the name of the super class is used to refer the sub class, which is our anonymous inner class in this case.

For reference,
Types of Inner Class
1. Regular Inner Class
2. Method Local Inner Class
3. Anonymous Inner Class
4. Static Nested Inner Class

Hope that the article helped solved your issues with this type of class. Remember Java Code Online is the key to a vast pool of Java. That's it for now. See you later.

1 comment:

  1. Very useful!!! it gives good explanation of anonymous inner classes.....

    ReplyDelete

Note: Only a member of this blog may post a comment.