Anonymous Inner Class in Java With Simple Example
An anonymous inner class in Java is an inner class which is declared without any class name at all. In simple words, a nameless inner class is called anonymous inner class.
Java anonymous inner classes are useful when we need only one object of the class.
Since an anonymous inner class does not have a name, it cannot have a constructor because we 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.
How to create Object of Anonymous inner class in Java?
Basically, an anonymous inner class in Java is a one-time class. We can define an anonymous inner class and create its object using the new operator at the same time in one step.
The general syntax to create anonymous inner class and its object in java is as follows:
Syntax:
new<interface-name or class-name>(argument-list) { // Anonymous class body }
Key points:
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. If 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 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 applications to implement event handling.
Note:
1. If the requirement is standard and required several times then you should go for a normal top-level class.
2. If the requirement is temporary and required only once (instant use), you should go for the anonymous inner class.
Features of Anonymous Inner Class
An anonymous inner class in Java is a special kind of 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 defined within a 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. They are as follows:
- Anonymous inner class that extends a class
- Anonymous inner class that implements an interface
Let's understand them with help of example programs one by one.
Anonymous inner class that extends class
Let's take an example program where we will declare an anonymous inner class that extends a class Fruits. Look at the source code to understand better.
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 a sour mango in 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 by which we can implement inside the above code.
1. First way is that 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. Second way is that 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:
Fruits f = new Fruits() { public void mango() { System.out.println("Sour"); // Overriding. } }; // Anonymous inner class ends here.
1. In line 1, Fruits f = new Fruits() { tells 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 a semicolon that ends the statement started on line 1.
Dot class file generated by the compiler:
There is a total of three dots class files 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 Interface
Let's take an example program where an anonymous inner class will implement an interface.
Program source code 2:
package anonymousClass; public interface Animal { // Abstract method does not have a body. public void food(); // No body. } 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(); } } 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:
Animal a = new Animal() { public void food() { System.out.println("Lion eats flesh"); // Overriding. } }; // 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 Java compiler:
import java.io.PrintStream; static class Lion$1 implements Animal { Lion$1() { } public void food() { System.out.println("Lion eats flesh"); } }
Restriction on Anonymous Inner class
An anonymous inner class also has the same restriction as to the local inner class with respect to its members.
- Anonymous inner class cannot be declared as public, private, protected, or static.
- It cannot access local variables of its enclosing scope that are not declared as final or effectively final.
- Inside anonymous inner classes, we cannot define any static variables, methods, or static blocks except for static final constant.
- We cannot create more than one object of the anonymous inner class in Java.
- 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
The difference between a normal class and an anonymous inner class in java is as follows:
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 a 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).
Hope that this tutorial has covered all the important points of anonymous inner class in java with example programs. I hope that you will have understood this topic nicely and enjoyed it.
Thanks for reading!!! Next ⇒ Static nested class in Java ⇐ PrevNext ⇒
Source: https://www.scientecheasy.com/2020/06/anonymous-inner-class-in-java.html/
0 Response to "Anonymous Inner Class in Java With Simple Example"
Post a Comment