【问题标题】:Java generics - restrict child class object stored in parent class argumentJava泛型 - 限制存储在父类参数中的子类对象
【发布时间】: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


【解决方案1】:

你总是可以随心所欲地抛出RuntimeExceptions,但你不应该,你很可能想要一个编译器错误来代替!?然后问题是:为什么? ChildParent,您可以对父级调用的所有内容也应该对子级起作用,请参见 SOLID 中的 L。

您也许可以通过使用泛型来实现这一点

class Parent<T> { 
    void method (T t) { ... }
}

class Child<T> extends Parent<T> {
    void somethingElse () { ... }
}

然后

Parent<A> p = new Parent<>();
Child<B> c = new Child<>();
A a = new A();
B b = new B();

p.method(a); // works
p.method(b); // compiler error

c.method(a); // compiler error
c.method(b); // works

但在这一点上,Child&lt;B&gt;Parent&lt;A&gt; 相比完全不同,而以前可以使用的 Parent p = c; 不再有效/可用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-04
    • 1970-01-01
    • 2022-10-14
    • 2021-06-27
    • 1970-01-01
    相关资源
    最近更新 更多