1


I have the following situation:

public class A {...};
public class B extends A {...};

And I defined a function inside a class C with the following header:

private void handleABC(final Collection<A>) {...}

but I get the following message when I try to call it passing type B:

The method handleABC(Collection) in the type C is not applicable for the arguments (Collection).

Should't this work for both A and B since I defined the method Collection<A> and B extends from A? What am I doing wrong?

Rexam
  • 823
  • 4
  • 23
  • 42

4 Answers4

3

B extends A, yes, but Collection<B> extends Collection<A> is not the case.

As someone mentioned in a comment, try Collection<? extends A>.

Robert
  • 277
  • 1
  • 16
2

change the handleABC() signature to

private void handleABC (final Collection<? extends A> )

so that the methods accepts Collection of subclasses of A.

Mihir
  • 572
  • 1
  • 6
  • 24
0

You must pass the class specified in diamond operator, not concrete classes or you can use "? extends A". You can read this link : https://docs.oracle.com/javase/tutorial/java/generics/inheritance.html

Cuong Bui
  • 36
  • 1
  • 4
0

Please review this answer: https://stackoverflow.com/a/897973/3465242

<T extends SomeClass>

when the actual parameter can be SomeClass or any subtype of it.

In your case

private void handleABC (final Collection<? extends A> )
Ashu
  • 2,066
  • 3
  • 19
  • 33