实现两个接口,一个匿名类 [英] implement two interfaces in an anonymous class

查看:290
本文介绍了实现两个接口,一个匿名类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个接口:

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)

这篇关于实现两个接口,一个匿名类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆