表示法:Inter
是接口(interface); Abs[N]
是一个抽象类。
以下代码在 Java 中运行良好,没有问题:
public class Impl<T extends Abs1<T>> extends Abs2<T> {...}
但是,如果你想在T
上引入另一个接口(interface)绑定(bind),我还没有找到任何简单的方法来做到这一点,即:
public class Impl<T extends Inter & Abs1<T>> extends Abs2<T> {...}
不起作用,因为 Abs1
作为抽象类不能用作边界参数。我发现的最简单但丑陋(丑陋吗?)的解决方案是:
public class Impl<B extends Inter, T extends Abs1<B>> extends Abs2<T> {...}
我有预感,在具有这些特征的 Scala 中存在更优雅的解决方案,但是对于 Java 有什么技巧吗?
最佳答案
哦天哪...好吧,这太尴尬了。我太专注于 F-Bound,以至于忘记了它直接来自 JLS, section 4.4 :
Every type variable declared as a type parameter has a bound. If no bound is declared for a type variable, Object is assumed. If a bound is declared, it consists of either:
a single type variable
T
, ora class or interface type
T
possibly followed by interface typesI1 & ... & In
.
换句话说,(抽象)类声明必须出现在交集类型中。所描述的行为与 F-Boundedness 无关。即,以下作品:
public class Impl<T extends Abs1<T> & Inter> extends Abs2<T> {...}
Java Tutorial 中也对此进行了描述。如果有人想一想,它是不言自明的,因此解析器有一种简单的方法来检查双重继承(这是被禁止的)。
关于Java F-Bound 通过接口(interface)绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42274896/