Sometimes you need a pure class, and to be instantiated only once in your code. When this is the case, you can use an anonymous inner class. It is called an inner class because it defined inside another class.
Anonymous inner class are the local inner classes that declared without a name, but an object of this class can be created. All of the code for the anonymous class is coded within the method where we need to create an instance of the anonymous class. Since anonymous inner classes do not have a name so you cannot use the new keyword in the usual way to create an instance of the class. Anonymous inner classes are declared and instantiated at the same time.
Anonymous inner classes can also be used to provide a similar facility as that provided by inner classes. Although anonymous inner classes result in more compact programs but they do make the code more difficult to read.
We’ll be covering the following topics in this tutorial:
Anonymous Inner Class Properties
Anonymous inner classes defined within methods rather than being members of an outer class. They are local to the methods, and you cannot mark them with any access modifier, like static, public, or private, like local method variables.
Anonymous inner classes always have to either implement interfaces or extend superclasses. You do not need to use the keywords implement or extends when you declare it. The anonymous inner class has to implement every abstract method in the interface or superclass.
Anonymous inner classes always use the no-arg, default constructor out of their superclasses to create instances. If the anonymous inner class used for the implementation of interfaces, they use java.lang.object().
Anonymous inner cases are compiled into classes called OuterClass- Namre$n.class – n is the running number of the inner classes inside the outer classes.
The advantage of using anonymous inner class fro event handling is that you can avoid large if-else statements to decide which component is being handled. Each component gets its own event handler so each event handler knows implicitly the component for which it is working.
We use the following syntax to construct instances of anonymous inner classes:
new SuperClassName/InterfaceName() {
// extends superclass or implements interface
// invoke the default no-arg constructor or Object[]
// Implement abstract methods in superclass/interface
// More methods if necessary……
}
The new operator followed by the name of an existing class or interface, followed by a set of parentheses. Next, you write the body of the class, enclosed in curly braces. The expression
creates an object that is an instance of a class that either extends the specified superclass or implements the specified interface. A reference to the object returned. (Notice that you do not use the extends or implements keywords in the expression.)
The instance that has been created may be used as a method argument or assigned to a variable.
Java Anonymous Class Example
class outer
{
private double i = 11.5 ;
private static String str = "Hi Java World";
public void display()
{
// Anonymous class
Object Obj=new Object()
{
public String toString()
{ return("Anonymous Class");}
};
System.out.println("i = " + i);
System.out.println("str = " + str);
System.out.println(Obj.toString());
}
}
class AnonymousClass
{
public static void main(String[] arga)
{
outer outobj = new outer(); //create instance of outer class
outobj.display();
}
}
Explanation: When this program compiled, there classes AnonymousClass.class, Outer.class and Outer$1.class are created. These numbers incremented for each anonymous class created by the compiler.
In this program,
new Object() {}
Declares and instantiates an anonymous class. The new keyword followed by the name of the class that specifies the type of object created from an anonymous class. It is followed by empty parentheses, which indicates no argument passed to the constructor of an anonymous class. The code of the class then follows it. An assignment statement can use an anonymous class as shown in the example. In that case, an anonymous class body is followed by a semicolon that marks the end of the assignment statement. The semicolon is part of an assignment statement, not the anonymous class. The following points should be kept in mind while working with anonymous inner classes.
The following points should be kept in mind while working with anonymous inner classes.
• Anonymous inner class cannot have explicit constructors because they have no name to give to the constructor.
• It cannot be public, protected, private or static.
• It cannot either extend a class or implement an interface.
• The anonymous inner class type must be either a subclass of the named type or implementation of the named interface.
• It cannot access static fields, methods or classes (with an exception that constant fields can be declared both static and final).
• It should use when only one instance of the class is needed, and the body of the class is concise.
• It is not a member of any enclosing classes. Rather than being declared along with other members, it is both declared and instantiated where an expression is legal, they must be kept short or fewer or readability will suffer.
• An anonymous class instance is occur in a non-static context.
• You can declare an anonymous class to implement only one interfaces at a time.
• The Clients of an anonymous class invoke only members that it inherits from its super class.
• An anonymous inner class must implement an interface or extend a superclass, but it cannot have an explicit extends or implements clause.
• An anonymous class must always implement all the abstract methods in the superclass or in the interface.
There are three types of anonymous inner class
• Anonymous inner class that extends Class.
• Anonymous inner class that implements interface.
• Anonymous inner class that defined inside method argument.
Difference between Anonymous class and Anonymous Inner class:
• In java, the typical class can extend a class and implement any number of interface simultaneously.
• In java, standard class, we can write any number of constructors.
Anonymous Classes
• In Java, we all encounter situations where we need to create an object but does not need to bother giving it an explicit name.
• With the inner classes, you can create and instantiate a class without bothering to give it a name. It is called an anonymous class.
• This unnamed get rid of additional named objects and makes the code more readable.
Anonymous Inner Classes:
• Anonymous inner classes don’t have a name, and their type must be either a extend another class or implement an interface.
• An anonymous inner class always created as part of a statement; don’t forget to enclose the statement with a curly brace.
• Anonymous inner class are the local inner classes that declared, defined, and automatically instantiated as part of a method invocation.
• In anonymous Inner class, we can’t write any constructor.