Home >Java >javaTutorial >Anonymous Class in Java
It is defining a class with no identity, i.e. a class without a name. They are used whenever you need to override the methods of a class, abstract class or interface. Anonymous inner class provides you with the blueprint, outline or template of the class but does not define or declare the behavior of the class. In this topic, we are going to learn about Anonymous Class in Java.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Let us look at some of the key concepts before proceeding.
One of the very important properties in an object-oriented language is Abstraction. Abstraction is the property that provides the blueprint/ template of methods, i.e. just declaration without defining them.
Java provides two such abstraction levels such as
Following are the examples of anonymous class in java:
Anonymous class for defining the method of an interface.
Code:
interface First { void printing(); } public class Test { public static void main(String[] args) { First obj = new First() { public void printing() { System.out.println("I am an inner class defining interface method"); } }; obj.printing(); } }
Output:
Explanation:
Anonymous class for defining the method of an abstract class.
Code:
abstract class AbstractClass { abstract class AbstractClass { public abstract void display(); } public class Test { public static void main(String[] args){ AbstractClass obj = new AbstractClass() { public void display() { System.out.println("I am an inner class defining abstract class method."); } }; obj.display(); } }
Output:
Explanation:
For the above Test class, a class file will be generated like normal named as Test.class.
For the anonymous inner class created, as there is no identity, a class file is still generated named as:
Test$1.class ---> anonymous class
If you create another anonymous inner class in the same class Test, then the class file will be named as:
Test$2.class
Some differences from normal classes:
Anonymous inner classes are mostly used in Graphic User Interface applications. When an object created has to be used only once, then the anonymous class can be used. When an object created has to be used only once, then the anonymous class can be used.
We can create an instance of an inner class object by first creating an object of outer class such as:
Outer class as Person so for creating an instance of an inner class inside person class
Person p = new Person(); Person.InnerClass innerClassObj = p.new InnerClass();
Anonymous inner class is a very important feature to know the power of object-oriented language and also is frequently asked questions in the technical interviews. Anonymous inner class gives you the liberty to define a class body method with no name.
The above is the detailed content of Anonymous Class in Java. For more information, please follow other related articles on the PHP Chinese website!