2016-04-25 6 views
1

私のJava多形性には錆びます。HashMapsを使用したJavaの多態性の例を理解していません

私はクラスの商品があり、それから商品を拡張するクラスの服がある場合、なぜ以下のことができないのですか?

私は、私はこのコンパイルエラーを取得していない
HashMap<String, Merchandise> stuff = new HashMap<String, Clothing>(); 

DataStore.java:5: error: incompatible types: HashMap<String,Clothing> cannot be converted to HashMap<String,Merchandise> 
     public static HashMap<String, Merchandise> tshirts = new HashMap<String, Clothing>(); 

も、商品アイテムのすべての衣料品ではありませんか? ^

+1

「衣類」とは何ですか?靴ではありません –

+0

服と商品の授業を精緻化できますか? –

+2

List のリストは、リストのサブクラスである可能性がありますか?なぜJavaのジェネリックは暗黙的に多相でないのですか?](http://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-arent-javas-generics-implicitly-p) – Savior

答えて

1

次のシナリオを検討してください:彼らは同じオブジェクトを参照するため

HashMap<String, Clothing> clothing = ... 
HashMap<String, Merchandise> merchandise = clothing; // Suppose this is allowed 
merchandise.put("Potato", new Potato()); 

おっと、商品にじゃがいもを入れて、それはまた、衣服に入りました!

+0

ありがとう、アンドリュー。意味がある。 –

1

あなたは、このように実行する必要があります。 HashMap<String,? extends merchandise> m=new HashMap<String,Clothing>();

HashMap<String, Merchandise>HashMap<String, Clothing>()>されていません。

関連する問題