Scientech Easy Anonymous Inner Class in Java | Example Programs | Scientech Easy

Wednesday, March 6, 2019

Anonymous Inner Class in Java | Example Programs

Anonymous Inner Class in Java


An anonymous inner class is an inner class which is declared without any class name at all. In other words, a nameless inner class is called an anonymous inner class in Java. Since it does not have a name, it cannot have a constructor because you know that a constructor name is the same as the class name.


Then how do we create an object of an anonymous class in Java if it does not have a constructor? Let's understand this concept.
Anonymous Inner Class in Java

How to create an object of an anonymous inner class in Java?


Basically, An anonymous inner class is a one-time class. We define an anonymous inner class and create its object using the new operator at the same time in one step. The general syntax of the declaration of an anonymous class and its object is given below.
Syntax:
         new<interface-name or class-name>(argument-list)
                {
                   // Anonymous class body
                 }
1. The new keyword is used to create an object of the anonymous inner class. It is always followed by either an existing class name or an existing interface name.
2. In the above syntax, if an interface name is used, it means that the anonymous class implements the interface.
3. If a class name is used, it means that the anonymous class extends from the class.
4. It the new keyword is followed by a class name then the argument list is used only. The argument list contains the actual parameter list which is used for calling a constructor of the existing class.
5. If the new keyword is followed by an interface name, it is left empty. 
6. Inside an anonymous class body, we can define variables, methods (if necessary), instance block, and local class.

Java Anonymous Inner Class Constructor


Since an anonymous inner class has no name, it is not possible to define a constructor for it within the class body.

When to use an Anonymous inner class in Java


In general, There are the following points that you should consider using an anonymous inner class instead of a local inner class.
1. The main purpose of using an anonymous inner class in java is just for instant use (i.e one-time usage).
2. An anonymous inner class can be used if the class has a very short body.
3. It can be useful if only one object of the class is required.
4. An anonymous inner class is useful when you are writing implementation classes for listener interfaces in graphics programming.
5. An anonymous inner class is the best suitable for GUI based application to implement event handling.

Note: If the requirement is standard and required several times then you should go for a normal top-level class.
If the requirement is temporary and required only once (instant use), you should go for the anonymous inner class. 

Features of an Anonymous Inner Class in Java


An anonymous inner class in Java is a special kind of an inner class with the following important features. They are as follows: 
1. When an anonymous inner class is created, Internally, its name is decided by the compiler which always extends a superclass or implements an interface. But it cannot have an explicit extends or implements clause.
2. It must implement all the abstract methods of the superclass or of the interface.
3. Internally, it always uses a default constructor from its superclass to create an object.
4. An anonymous inner class is compiled by a class named OuterClassName$n. For example, if the outer class Student has two anonymous inner classes, they are compiled into Student$1.class and Student$2.class.
5. Like the local inner class, an anonymous inner class can also access the members of its outer class.

Types of Anonymous Inner Class in Java


Based on declaration and behavior, an anonymous inner class in Java comes into two flavors.
1. Anonymous inner class that extends a class
2. Anonymous inner class that implements an interface

Anonymous inner class that extends a class


Let's consider the below an example program to understand this concept.
Program source code 1:
    package anonymousClass; public class Fruits { public void mango(){ System.out.println("Sweet"); } // Suppose we also declared here 9 more types of fruits method. So the total number of fruits method is 10. }
Suppose we need mango sour taste for a one-time temporary requirement. Except for this method, the remaining 9 methods we also want as it is. Then how will you implement this in the above code?
There are two ways to implement in the above code.
1. We will create a class that will extend the Fruits class and overrides the mango method. But this technique is suitable for the permanent requirement, not for the temporary requirement.
2. We will use an anonymous inner class concept for a one-time temporary requirement.
    package anonymousClass; public class Taste { public static void main(String[] args) { // Here we are using an anonymous inner class that extends a class Fruits. Fruits f=new Fruits(){ // Here, Overriding the mango() method of Fruits class. public void mango(){ System.out.println("Sour"); // Overriding. } }; // Anonymous inner class ends here. A semi-colon is necessary to end the statement. f.mango(); // This object is created for Fruits class. Fruits f1=new Fruits(); f1.mango(); // It will print sweet. } }
    Output: Sour Sweet
Internal working of given code:
    Line 1: Fruits f=new Fruits(){ Line 2: public void mango() Line 3: { Line 4: System.out.println("Sour"); // Overriding. Line 5: } Line 6: }; // Anonymous inner class ends here.
1. In line 1, Fruits f=new Fruits(){ tell us that an object of the anonymous class is created that is referred by a reference variable f of type Fruits. Then declare a new class but its name is decided by the compiler that extends the fruits class and provides the implementation (i.e overriding) of mango() method. 
In line 1, there is also a curly brace that opens the class definition.
2. In line 2, within the new class definition, we are overriding the mango() method of the superclass Fruits. 
3. In line 4, Statement within the overriding mango() method.
4. In line 5, we are closing curly brace of the mango() method.
5. Line 6 includes a curly brace closing off the anonymous inner class definition. But curly brace also contains semicolon that ends the statement started on line 1. 

Dot class file generated by the compiler:
There is a total of three dot class file generated by the compiler.1. First dot class file generated by the compiler for Fruits class is Fruits.class.
2. Second dot class file generated by the compiler for Taste class is Taste.class.
3. One dot class file is also generated for the anonymous inner class. Since it is present in the Taste class. Therefore, Taste class is the outer class of the anonymous inner class. So, the dot class file for the anonymous inner class is Tatse$1.class. 1 represents the first anonymous inner class.

Internal class generated by the compiler:
    import java.io.PrintStream; static class Taste$1 extends Fruits { Taste$1() { } public void mango(){ System.out.println("Sour"); } }

Anonymous inner class that implements an interface


Program source code 2:
    package anonymousClass; public interface Animal { // Abstract method does not have a body. public void food(); // No body. } package anonymousClass; public class Lion { // Here we are using an anonymous inner class that implements an interface Animal. Animal a=new Animal(){ public void food(){ System.out.println("Lion eats flesh"); // Overriding food method of Interface Animal. } }; public void display(){ a.food(); } } package anonymousClass; public class Test { public static void main(String[] args){ Lion l=new Lion(); l.display(); // 1st method to call an anonymous function by local class method. l.a.food(); // 2nd method to call an anonymous function directly. } }
    Output: Lion eats flesh Lion eats flesh
Internal working of given code:
    Line 1: Animal a=new Animal(){ Line 2: public void food() Line 3: { Line 4: System.out.println("Lion eats flesh"); // Overriding. Line 5: } Line 6: }; // Anonymous inner class ends here.
1. Line 1 tells us that an object of the anonymous class is created that is referred by a reference variable 'a' of type Animal. Then declare a new class but its name is decided by the compiler that implements the Animal class and provides the implementation (i.e overriding) of food() method. 
2. In line 2, within the new class definition, we are overriding the food() method of the superclass Animal.

Internal class generated by the compiler:

    import java.io.PrintStream; static class Lion$1 implements Animal { Lion$1() { } public void food(){ System.out.println("Lion eats flesh"); } }

Restriction on an Anonymous inner class in Java


An anonymous inner class also has the same restriction as the local inner class with respect to its members.
1. Anonymous inner class cannot be public, private, protected or static.
2. It cannot access the local variables of its enclosing scope that are not declared as final or effectively final.
3. Inside anonymous inner classes, we cannot define any static variables, methods, or static blocks except for static final constant.
4. We cannot create more than one object of the anonymous inner class in Java.
5. Since an anonymous inner class has no name. Therefore, we cannot declare a constructor for it within the class body.

Difference between Normal/Regular class and Anonymous Inner class


1. A normal Java class can implement any number of interfaces simultaneously but an anonymous inner class can implement only one interface at a time.
2. A normal Java class can extend a class and can implement any number of interfaces simultaneously but an anonymous inner class can extend a class or can implement an interface but not both simultaneously.
3. In normal Java class, we can define any number of constructors but in an anonymous inner class, we cannot write any constructor explicitly (because the name of the class and name of the constructor must be the same but anonymous inner class not having any name).

Final words
Hope that this article has covered all the important topics of anonymous inner class in java with practical example programs. We hope that this article is useful for you and will have enjoyed reading this article. I always try to understand you on the level my best.
Thanks for reading!