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

编程入门 行业动态 更新时间:2024-10-28 03:32:11
本文介绍了实现两个接口,一个匿名类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个接口:

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.

推荐答案

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

更多推荐

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

本文发布于:2023-06-08 03:49:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/576115.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!