为什么匿名类不能直接实现多个接口?仅仅因为语法还是有另一个原因? [英] Why an Anonymous class can't implement multiple interfaces directly? Simply because of syntax or there is another reason?
问题描述
有一个内部问题,为什么java匿名类不能同时实现和子类?或者只是因为语法?
In there an internal issue why java anonymous classes cannot implement and subclass at the same time? Or is it just because the syntax?
推荐答案
在那里有一个内部问题为什么java匿名类不能同时实现和子类?
我认为由于语法原因它是99%。类型参数甚至支持交叉点类型(< T扩展InterfaceX& InterfaceY>
)所以我认为这样的功能不会引入任何矛盾或复杂情况。
I believe it is 99% due to syntactical reasons. Type parameters even support intersection types (<T extends InterfaceX & InterfaceY>
) so I don't think such feature would introduce any contradictions or complications.
像 new(InterfaceX& InterfaceY)(){...}
这样的表达式可以编译成像
An expression like new (InterfaceX & InterfaceY)() { ... }
could for instance be compiled into something like
interface InterfaceXandY extends InterfaceX, InterfaceY {}
... new InterfaceXandY() { ... }
没有添加此类功能的原因很可能是因为这是一个罕见的用例,其中有一个简单的解决方法。
The reason no such feature has been added is most likely because it's a rare use case for which there is a simple workaround.
有点相关的说明。你可以让一个lambda工具实例 Serializable
通过做
On a somewhat related note. You can let a lambda implement for instance Serializable
by doing
Runnable r = (Runnable & Serializable)() -> System.out.println("Serializable!");
这篇关于为什么匿名类不能直接实现多个接口?仅仅因为语法还是有另一个原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!