Jordan Baron
Jordan Baron

Reputation: 161

Java HashMap with Object as value along with anything that extends it?

I have a HashMap that takes a string as a key and an object as the value, in this case a class I made called ItemBuilder. I can put another class that extends it as a value, but I can't use any of the methods that the class has. Why is this?

HashMap<String, ItemBuilder> registry = new HashMap<String, ItemBuilder>();
registry.put("ZEUS_BOLT", new ZeusBolt());
registry.get("ZEUS_BOLT").testLog();

Upvotes: 0

Views: 32

Answers (1)

Amongalen
Amongalen

Reputation: 3131

When you check documentation for Map, you will see that a for Map<K, V>, method is deplared as V get(Object key). This means that get returns object of type specified in variable declaration, in your case ItemBuilder.

I'm assuming that ItemBuilder doesn't have a testLog method, it is defined in ZeusBolt. From get you are getting a ItemBuilder object.

If you want to be able to call testLog you need cast it to a proper type like so:

ZeusBolt zeusBolt = (ZeusBolt) registry.get("ZEUS_BOLT");
zeusBolt.testLog();

In case you have objects of different types in the map and want to iterate over all of them and do approriate operation based on type, you might be interested in instanceof operator to check if variable is of given type:

ItemBuilder itemBuilder = registry.get("ZEUS_BOLT");
if (itemBuilder instanceof ZeusBolt){
    ZeusBolt zeusBolt = (ZeusBolt) itemBuilder;
    zeusBolt.testLog();
}

Upvotes: 1

Related Questions