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