怎么创建anonymous class
时间: 2023-10-20 08:18:12 浏览: 45
在 Java 中,可以使用以下语法创建匿名类:
```
new <class or interface>() {
// class or interface methods and variables
};
```
例如,我们可以创建一个匿名的 Runnable 类:
```
Runnable r = new Runnable() {
public void run() {
System.out.println("This is an anonymous class.");
}
};
```
在这个例子中,我们定义了一个匿名的 Runnable 类,并重写了 run() 方法。然后,我们将这个匿名类的实例分配给一个变量 r。此时,我们可以通过调用 r.run() 方法来执行这个匿名类中重写的 run() 方法。
相关问题
anonymous class
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.
Anonymous class implements interface; cannot have qualifier for new 这个报错是什么
这个错误通常是由于在创建匿名类时,使用了限定符号(qualifier),例如使用了类的完全限定名(fully qualified name),而这是不允许的。匿名类是一个实现接口或继承类的临时类,它没有名称,并且不能被显式引用或实例化,因此不能使用限定符号。
例如,以下代码将会导致这个错误:
```
MyInterface obj = new MyInterface() { // 匿名类
com.example.MyClass myClassInstance = new com.example.MyClass(); // 错误:不能使用限定符号
// 实现 MyInterface 接口的方法
public void myMethod() {
myClassInstance.doSomething();
}
};
```
正确的写法是:
```
MyInterface obj = new MyInterface() { // 匿名类
// 实现 MyInterface 接口的方法
public void myMethod() {
com.example.MyClass myClassInstance = new com.example.MyClass(); // 在方法内部创建对象
myClassInstance.doSomething();
}
};
```
这样就可以避免这个错误。