So I've been reading through the Generics tutorial offered by Oracle here: http://docs.oracle.com/javase/tutorial/java/generics/
And I've tried running my own example to make sure I understand how to use Generics. I have the following code:
import java.util.*;
public class Generics {
class NaturalNumber {
private int i;
public NaturalNumber(int i) { this.i = i; }
}
class EvenNumber extends NaturalNumber {
public EvenNumber(int i) {
super(i);
}
}
public static void main(String[] args) {
Collection<? extends NaturalNumber> c = new ArrayList<>();
c.add(new EvenNumber(2)); //this line produces a compile time error
}
}
My goal is to be able to add any object which is a subtype of NaturalNumber to the Collection c. I'm not sure why this doesn't work and reading through Oracle's tutorial hasn't enlightened me either.
When you have ? extends NaturalNumber
, the parameter could be some other subclass of NaturalNumber
that is in no way related to EvenNumber
. For instance,
Collection<? extends NaturalNumber> c = new ArrayList<OtherNaturalNumber>();
is valid if OtherNaturalNumber
extends NaturalNumber
.
Consequently, you are not able to add an EvenNumber
instance to the list. You can just use this declaration:
Collection<NaturalNumber> c = new ArrayList<>();
which will allow you to add any NaturalNumber
instance (including an EvenNumber
).
On another note, you probably meant to make those nested classes static
(or don't nest them at all).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With