Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java泛型-限制父类参数中存储的子类对象_Java_Generics_Inheritance_Restriction - Fatal编程技术网

Java泛型-限制父类参数中存储的子类对象

Java泛型-限制父类参数中存储的子类对象,java,generics,inheritance,restriction,Java,Generics,Inheritance,Restriction,我有父类和(子扩展父类)类。 我还有类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 Ch

我有父类和(子扩展父类)类。 我还有类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
要求如下:

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方法(a)和p方法(b)成功地工作

是否可以使用泛型实现此行为? 如有任何建议,我们将不胜感激


谢谢。

您可以根据自己的意愿随时抛出
运行时异常,但不应该这样做,您很可能希望出现编译器错误!?然后问题是:为什么?
子级
父级
,您可以对父级调用的所有内容也应适用于子级,请参见实心L

通过使用

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

class Child<T> extends Parent<T> {
    void somethingElse () { ... }
}
类父{
无效方法(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
Parent p=newparent();
Child c=新的Child();
A=新的A();
B=新的B();
p、 方法(a);//作品
p、 方法(b);//编译错误
c、 方法(a);//编译错误
c、 方法(b);//作品

但是在这一点上,
子项
父项
父项p=c完全不同不再有效/可用。

似乎您的父类和子类违反了Liskov替换原则。我强烈建议您重新考虑此设置。这不是运行时异常,而是编译错误。