一个匿名类如何实现两个(或更多)接口?或者,如何同时扩展类和实现一个接口?例如,我想创建一个匿名类的对象,它扩展了两个接口:
// Java 10 "var" is used since I don't know how to specify its type
var lazilyInitializedFileNameSupplier = (new Supplier<String> implements AutoCloseable)() {
private String generatedFileName;
@Override
public String get() { // Generate file only once
if (generatedFileName == null) {
generatedFileName = generateFile();
}
return generatedFileName;
}
@Override
public void close() throws Exception { // Clean up
if (generatedFileName != null) {
// Delete the file if it was generated
generatedFileName = null;
}
}
};
然后我可以在try-with-resources块中使用它作为AutoCloseable
作为延迟初始化的实用程序类:
try (lazilyInitializedFileNameSupplier) {
// Some complex logic that might or might not
// invoke the code that creates the file
if (checkIfNeedToProcessFile()) {
doSomething(lazilyInitializedFileNameSupplier.get());
}
if (checkIfStillNeedFile()) {
doSomethingElse(lazilyInitializedFileNameSupplier.get());
}
}
// By now we are sure that even if the file was generated, it doesn't exist anymore
我不想创建一个内部类,因为我绝对确定这个类不会在任何地方使用,除了我需要在其中使用它的方法(而且我可能还想使用在该方法中声明的可能是var
类型的局部变量)。
发布于 2011-05-01 21:04:40
匿名类必须扩展或实现一些东西,就像任何其他Java类一样,即使它只是java.lang.Object
。
例如:
Runnable r = new Runnable() {
public void run() { ... }
};
在这里,r
是实现Runnable
的匿名类的对象。
匿名类可以使用相同的语法扩展另一个类:
SomeClass x = new SomeClass() {
...
};
您不能做的是实现多个接口。要做到这一点,需要一个命名类。但是,匿名内部类和命名类都不能扩展多个类。
发布于 2011-05-01 21:06:00
匿名类通常实现一个接口:
new Runnable() { // implements Runnable!
public void run() {}
}
JFrame.addWindowListener( new WindowAdapter() { // extends class
} );
如果你的意思是你是否可以实现2个或更多的接口,那么我认为这是不可能的。然后,您可以创建一个结合了这两者的私有接口。尽管我很难想象为什么你会希望一个匿名类有这样的东西:
public class MyClass {
private interface MyInterface extends Runnable, WindowListener {
}
Runnable r = new MyInterface() {
// your anonymous class which implements 2 interaces
}
}
发布于 2011-05-01 21:06:32
匿名类总是扩展超类或实现接口。例如:
button.addActionListener(new ActionListener(){ // ActionListener is an interface
public void actionPerformed(ActionEvent e){
}
});
此外,尽管匿名类不能实现多个接口,但您可以创建一个扩展其他接口的接口,并让您的匿名类来实现它。
https://stackoverflow.com/questions/5848510
复制相似问题