So, I was looking through the Oracle Java Tutorials, specifically this piece of code;
List<EvenNumber> le = new ArrayList<>();
List<? extends NaturalNumber> ln = le;
ln.add(new NaturalNumber(35)); // compile-time error
which can be found here. It is my understanding (and please correct me if I'm wrong) that the above code will not work because the compiler does not know that ln
refers to a List of EvenNumbers and so this prevents you from accidentally adding any object that could be a supertype of the elements that are meant for the List. IF that is the case, then why is it that if you have a statement like Number num = new Integer(6);
the compiler is able to correctly determine that num is an Integer object if you write an if statement like so;
if (num instanceof Integer) {...}
?
I guess my question is, how is the compiler able to determine that num
is referring to an Integer
object in the second example, but not able to determine that ln
is referring to a List<EvenNumber>
object in the first example?