为什么接受Foo <parent>的方法不接受Foo <child>但接受Parent的方法接受Child?

时间:2015-06-26 20:15:39

标签: java generics

(首先,如果有些措辞很糟糕,我很抱歉,我不知道该怎么称呼这些东西,如果你有更好的想法我可以留下评论,我可以编辑。)

今天我在Example1中遇到了类似下面的问题。如果你有一个被声明为具有泛型允许类型(Foo<Bazz> foo = new Foo<Bazz>();)的子类的泛型,那么如果你将它赋给一个只接受泛型父类型的方法,它将产生编译时错误({{1 }})。

method1(Foo<Bar> foo)
  

错误:类型public class Example1 { public static void main(String[] args) { Foo<Bazz> foo = new Foo<Bazz>(); method1(foo); // Compilation error below } public static void method1(Foo<Bar> foo) { {} public static class Foo<B extends Bar> {} public static class Bar {} public static class Bazz extends Bar {} } 中的方法method1(Example1.Foo<Example1.Bar>)不适用于参数Example1

这对我来说很奇怪,因为以下工作正常。您可以创建一些子类型((Example1.Foo<Example1.Bazz>))和接受父类的方法({{1仍然会接受它。

Child c = new Child();

为什么我可以将子类型传递给要求父类型的参数但不将具有子类型的泛型传递给要求使用父类型的泛型的参数?

我确定这只是一些标准,但为什么呢? method2(Parent p)public class Example2 { public static void main(String[] args) { Child c = new Child(); method2(c); } public static void method2(Parent p) {} public static class Parent {} public static class Child extends Parent {} } 的{​​{1}}类似Foo<Bazz>是不是Foo<Bar>

0 个答案:

没有答案