实现两个接口,一个匿名类接口、两个

2023-09-05 11:06:35 作者:星星笑我、太天真

我有两个接口:

interface A {
    void foo();
}

interface B {
    void bar();
}

我能够创建类实现任一接口,像这样的匿名实例:

I am able to create anonymous instances of classes implementing either of these interfaces like so:

new A(){
    void foo(){}
}

new B(){
    void bar(){}
}

我要创建一个实现这两个接口一个匿名类。喜欢的东西(虚拟):

I want to create an anonymous class that implements both interfaces. Something like (the fictitious):

new A implements B {
    void foo(){}
    void bar(){}
}

这显然给出了一个编译器错误:B不能被解析为一个类型

This obviously gives a compiler error: "B cannot be resolved to a type".

解决方法很简单:

class Aggregate implements A, B {
    void foo(){}
    void bar(){}
}

然后我用骨料在以往我会用匿名类。

I then use Aggregate where ever I would have used the anonymous class.

我在想,如果它是甚至法律为实现两个接口,一个匿名类。

I was wondering if it is even legal for an anonymous class to implement two interfaces.

推荐答案

一个匿名内部类可以扩展一个子类或实现一个 接口。不像非匿名类(内或以其他方式),一个匿名 内部类不能两者都做。换句话说,它不能同时扩展类和 实现一个接口,也可以实现一个以上的接口。 ( http://scjp.wikidot.com/nested-classes )

"An anonymous inner class can extend one subclass or implement one interface. Unlike non-anonymous classes (inner or otherwise), an anonymous inner class cannot do both. In other words, it cannot both extend a class and implement an interface, nor can it implement more than one interface. " (http://scjp.wikidot.com/nested-classes)

 
精彩推荐