Curriculum
In Java, an anonymous class is a class that is defined and instantiated in a single expression, without a name. Anonymous classes are used to create one-time use objects that implement or extend a particular class or interface.
Here’s an example of an anonymous class in Java:
public class HelloWorld { public void sayHello() { System.out.println("Hello World!"); } public static void main(String[] args) { HelloWorld hw = new HelloWorld() { public void sayHello() { System.out.println("Hello from anonymous class!"); } }; hw.sayHello(); } }
In this example, we define a class HelloWorld
with a method sayHello()
. Then, in the main()
method, we create an anonymous class that extends HelloWorld
and overrides the sayHello()
method. We create an instance of the anonymous class and call the sayHello()
method, which prints “Hello from anonymous class!” to the console.
Here are some rules to keep in mind when working with anonymous classes in Java:
Overall, anonymous classes can be useful in Java when you need to create a one-time use object that implements or extends a particular class or interface. By defining and instantiating the class in a single expression, you can create an object without needing to create a named subclass or implement a separate interface.