1

I'm rusty on my Java polymorphism.

If I have a class Merchandise, and then a class Clothing that extends Merchandise, why aren't I able to do the following?

HashMap<String, Merchandise> stuff = new HashMap<String, Clothing>();

When I do so, I am getting this compilation error:

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>();

Aren't all Clothing items also Merchandise items? ^

A B
  • 131
  • 1
  • 13
  • 1
    what is `Clothing` ? Not a Shoe – Scary Wombat Apr 25 '16 at 04:59
  • Can you elaborate the classes Clothing and Merchandise? – Pritam Banerjee Apr 25 '16 at 05:00
  • 2
    Possible duplicate of [Is List a subclass of List? Why aren't Java's generics implicitly polymorphic?](http://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-arent-javas-generics-implicitly-p) – Savior Apr 25 '16 at 05:03
  • Yeah, that link is very helpful, Pillar. I just wasn't searching on the right terms to hit it. Sorry for the duplication. – A B Apr 25 '16 at 05:21

2 Answers2

1

Consider the following scenario:

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

Uh-oh, by putting potato into merchandise, it has also gone into clothing, because they reference the same object!

Andrew Williamson
  • 8,299
  • 3
  • 34
  • 62
1

You need to do like this: HashMap<String,? extends merchandise> m=new HashMap<String,Clothing>();

HashMap<String, Merchandise> IS NOT a HashMap<String, Clothing>()>.

ProblemSolver
  • 161
  • 1
  • 1
  • 10