Search code examples
javaclassdictionaryextendsinventory

Extended classes in a map (java)


I'm trying to make a basic inventory system in java. The items that are all keys to a map and all extend the UsableItem class. For example, Tophat extends UsableItem. The problem is I can't save the myTophat item/object into it without making the key type Tophat, thereby not being able to store other types of items. How do I make my map to store everything that extends UsableItem?


Solution

  • You declare it this way:

    Map<UsableItem, SomeObject> map;
    

    Then you can add as keys whatever objects of type UsableItem or sub-types of it.