我对 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>();
所有的服装元素不都是商品吗? ^
最佳答案
考虑以下场景:
HashMap<String, Clothing> clothing = ...
HashMap<String, Merchandise> merchandise = clothing; // Suppose this is allowed
merchandise.put("Potato", new Potato());
呃哦,通过将土 bean 放入商品中,它也进入了服装中,因为它们引用了同一个对象!
关于java - 不理解涉及 HashMap 的 Java 多态性示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36832267/