Reputation: 913
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?
Upvotes: 1
Views: 104
Reputation: 36
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
Upvotes: 0
Reputation: 2266
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> )
Upvotes: 0
Reputation: 581
change the handleABC()
signature to
private void handleABC (final Collection<? extends A> )
so that the methods accepts Collection of subclasses of A.
Upvotes: 2
Reputation: 307
B extends A
, yes, but Collection<B> extends Collection<A>
is not the case.
As someone mentioned in a comment, try Collection<? extends A>
.
Upvotes: 3