Method with typed list and inheritance

I have some problems with a method with a typed List parameter inherited from another (typed) class.

Let it be simple:

public class B<T> { public void test(List<Integer> i) { } } 

Class B has a useless generic T, and test () is an integer list.

Now if I do:

 public class A extends B { // don't compile @Override public void test(List<Integer> i) { } } 

I get a "Type A Method Test (List) method must override or implement a supertype method" error, this should not be.

But deleting the list type works ... although it does not depend on the general class.

 public class A extends B { // compile @Override public void test(List i) { 

And also the definition of useless common below to use a typed list

 public class A extends B<String> { // compile @Override public void test(List<Integer> i) { 

So, I do not know, general B should not affect the list type test (). Does anyone have an idea of ​​what is going on?

thanks

+6
source share
2 answers

You are extending the original type B, not the generic one. The raw method does not have the test(List<Integer> i) method, but test(List) .

If you switch to raw types, all generics are replaced with raw, regardless of whether their type was filled or not.

To do it right, do

  public class A<T> extends B<T> 

This will use the generic type B<T> , which includes the method you want to override.

+8
source

When deleting, use a class without generics (and use its raw), all generics from class methods are forgotten.

For this reason, when you report a generic type in the second case, you get it working.

It:

 class T<G> { public void test(G g); } 

in this case:

 class A extends T { } 

will look like this:

 class T { public void test(Object g); } 

It was a java puzzle introduced in Google IO 2011, where you can see the video here

+1
source

Source: https://habr.com/ru/post/919244/


All Articles