General concepts: problems with adding SubClass objects to collections

So, I read the Generics tutorial offered by Oracle here: http://docs.oracle.com/javase/tutorial/java/generics/

And I tried to run my own example to make sure that 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 add any object that is a subtype of NaturalNumber to collection c. I'm not sure why this is not working, and reading through an Oracle tutorial also did not illuminate me.

+4
source share
3 answers

If you have ? extends NaturalNumber ? extends NaturalNumber , this parameter may be some other subclass of NaturalNumber that is in no way associated with EvenNumber . For instance,

 Collection<? extends NaturalNumber> c = new ArrayList<OtherNaturalNumber>(); 

valid if OtherNaturalNumber continues to NaturalNumber .

Therefore, you cannot add an instance of EvenNumber to the list. You can simply use this declaration:

 Collection<NaturalNumber> c = new ArrayList<>(); 

which allows you to add any instance of NaturalNumber (including EvenNumber ).

In another note, you'd probably want to make these nested classes static (or not at all).

+7
source

Collection<? extends NaturalNumber> First Collection<? extends NaturalNumber> must be Collection<NaturalNumber> . Instances of EvenNumber (either any NaturalNumber or a subtype of NaturalNumber ) can be placed in a collection this way.

Essentially Collection<? extends NaturalNumber> Collection<? extends NaturalNumber> says that the Collection type parameter type continues with NaturalNumber . So let's say that the class OddNumber extends NaturalNumber , then the type of the parameter of type Collection can be OddNumber , which EvenNumber cannot be safely distinguished.

However, there is another compiler error. For use in a static context or main(String[]) each of the inner classes NaturalNumber and EvenNumber must have a static modifier placed in each class declaration.

+1
source

Your problem is that you told the compiler that the type of the Collection element could be any type of extends NaturalNumber , but then you tried to insert an object into it. As far as the compiler knows, c is Collection<OddNumber> , and you just added EvenNumber !

0
source

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


All Articles