0

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

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

If I wanted to grab an item from the registry based on user input, how would I do so? Say if I had a ZeusBolt and a Sword class, both extending ItemBuilder, would I have to have if statements checking for every type?
@JordanBaron Yes, if you want to call different methods you have to do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.