如果我有这样的类(class)
class SuperType {}
class SubTypeOne extends SuperType {}
class SubTypeTwo extends SuperType {}
我想做一个这样的界面
interface TypeHandler {
public void handle(SuperType arg);
}
但允许这些是有效的实现
class SubTypeOneHandler implements TypeHandler {
public void handle(SubTypeOne arg) { }
}
如您所见,使用接口(interface)中定义的参数类型的子类。
我尝试使用重写界面
interface TypeHandler {
public void handle(? extends SuperType arg);
}
但看起来这不是有效的 java。
最佳答案
这从根本上来说是不安全的;如果接口(interface)被声明为接受 SuperType
,则您必须能够使用 SuperType
的任何子类调用任何实现。
您真正想要的是每个子类型都有一个不同的、类型安全的接口(interface)版本。
这就是泛型的用途;您需要使界面通用。
关于java - 接口(interface)允许任何子类参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55730607/