在 Java 中,匿名类可以扩展另一个类吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10479010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Java, can anonymous classes extend another class?
提问by user810430
Code like:
代码如:
protected Interface1 varClass1 = new Interface1() {
But I would also like that this anonymous nested class also extends the class Base
, something like:
但我也希望这个匿名嵌套类也扩展了 class Base
,例如:
protected Interface1 varClass1 = new Interface1() extends Base {
....
Is this possible in Java?
这在Java中可能吗?
回答by NPE
An anonymous class can either implement exactly one interface orextend one class.
匿名类可以只实现一个接口或扩展一个类。
One workaround is to create a named class that extends Base
and implements Interface1
, and then use that as the base class for the anonymous class:
一种解决方法是创建一个扩展Base
和实现的命名类,Interface1
然后将其用作匿名类的基类:
public abstract class Base1 extends Base implements Interface1 {}
...
protected Interface1 varClass1 = new Base1() {
...
回答by rolve
While it is not possible to both extend a class and implement an interface, what you probably what to do can be achieved using delegation.
虽然扩展类和实现接口是不可能的,但您可能要做的事情可以使用委托来实现。
Just create an instance of Base
in the initializer of your anonymous class and use its methods from the methods you implement from Interface1
.
只需Base
在匿名类的初始值设定项中创建一个实例,并从您实现的方法中使用其方法Interface1
。
EDIT: My answer assumes that you only want to inherit from Base
because of its implementation, not because of its interface. This is a valid assumption given that the interface of Base
is not visible after assigning the object to a Interface1
variable. Therefore, I think it's better to use delegation here instead of creating a new class.
编辑:我的回答假设您只想Base
从其实现继承,而不是因为它的接口。这是一个有效的假设,因为Base
在将对象分配给Interface1
变量后接口不可见。因此,我认为这里最好使用委托,而不是创建一个新类。