2016-04-25 22 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 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>()>