【发布时间】:2021-02-16 17:35:33
【问题描述】:
我有 Parent 和 (Child extends Parent) 类。 我还有 A 类和(B 扩展 A)类。
有以下代码设置:
class Parent {
method (A a) {
//some actions
}
}
class Child extends Parent {
method (B b) {
super.method(b)
// some additional actions
}
}
假设我们有以下内容:
Parent p = new Parent();
Child c = new Child();
A a = new A();
B b = new B();
要求如下:
p.method(a); // success
p.method(b); //RunTimeException
c.method(a); //RunTimeException
c.method(b); //success
这里的主要问题是 c.method(a) 和 p.method(b) 成功。
是否可以使用泛型来实现这种行为? 任何建议表示赞赏。
谢谢。
【问题讨论】:
-
似乎您的父类和子类违反了 Liskov 替换原则。我强烈建议您重新考虑此设置。
-
这不是RuntimeException,而是编译错误。
标签: java generics inheritance restriction