ska*_*man 94
匿名类必须像任何其他Java类一样扩展或实现某些东西,即使它只是java.lang.Object.
例如:
Runnable r = new Runnable() {
public void run() { ... }
};
Run Code Online (Sandbox Code Playgroud)
这里,r是一个实现的匿名类的对象Runnable.
匿名类可以使用相同的语法扩展另一个类:
SomeClass x = new SomeClass() {
...
};
Run Code Online (Sandbox Code Playgroud)
你不能做的是实现多个接口.你需要一个命名类来做到这一点.但是,匿名内部类和命名类都不能扩展多个类.
ext*_*eon 35
匿名类通常实现一个接口:
new Runnable() { // implements Runnable!
public void run() {}
}
JFrame.addWindowListener( new WindowAdapter() { // extends class
} );
Run Code Online (Sandbox Code Playgroud)
如果你的意思是你是否可以实现2个或更多接口,那么我认为这是不可能的.然后,您可以创建一个将两者结合在一起的私有界面.虽然我不能轻易想象你为什么要一个匿名类来拥有它:
public class MyClass {
private interface MyInterface extends Runnable, WindowListener {
}
Runnable r = new MyInterface() {
// your anonymous class which implements 2 interaces
}
}
Run Code Online (Sandbox Code Playgroud)
MBy*_*ByD 16
匿名类总是扩展超类或实现接口.例如:
button.addActionListener(new ActionListener(){ // ActionListener is an interface
public void actionPerformed(ActionEvent e){
}
});
Run Code Online (Sandbox Code Playgroud)
此外,尽管匿名类无法实现多个接口,但您可以创建扩展其他接口的接口,并让您的匿名类实现它.
thi*_*goh 15
我想没有人理解这个问题。我猜这家伙想要的是这样的:
return new (class implements MyInterface {
@Override
public void myInterfaceMethod() { /*do something*/ }
});
Run Code Online (Sandbox Code Playgroud)
因为这将允许诸如多个接口实现之类的东西:
return new (class implements MyInterface, AnotherInterface {
@Override
public void myInterfaceMethod() { /*do something*/ }
@Override
public void anotherInterfaceMethod() { /*do something*/ }
});
Run Code Online (Sandbox Code Playgroud)
这确实很好;但这在 Java 中是不允许的。
您可以做的是在方法块中使用本地类:
public AnotherInterface createAnotherInterface() {
class LocalClass implements MyInterface, AnotherInterface {
@Override
public void myInterfaceMethod() { /*do something*/ }
@Override
public void anotherInterfaceMethod() { /*do something*/ }
}
return new LocalClass();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
96515 次 |
| 最近记录: |