anonymous class
时间: 2023-10-12 12:10:33 浏览: 53
An anonymous class in Java is a local inner class that does not have a name. It is defined and instantiated at the same time as a single expression. Anonymous classes are commonly used when implementing interfaces or extending abstract classes that have only one or a few methods. They are also often used for event handling in graphical user interfaces (GUIs). The syntax for defining an anonymous class is as follows:
```
interface MyInterface{
void myMethod();
}
class MyClass{
void myMethod(){
MyInterface anonymousClass = new MyInterface(){
public void myMethod(){
System.out.println("This is an anonymous class!");
}
};
anonymousClass.myMethod();
}
}
```
In this example, an anonymous class is defined and instantiated at the same time as a single expression within the `myMethod()` method of the `MyClass` class. The anonymous class implements the `MyInterface` interface and provides an implementation for the `myMethod()` method. When the `myMethod()` method is called on the anonymous class object, it prints the message "This is an anonymous class!" to the console.