In Java, how do I override the class type of a variable in an inherited class? For example:
class Parent {
protected Object results;
public Object getResults() { ... }
}
class Child extends parent {
public void operation() {
... need to work on results as a HashMap
... results.put(resultKey, resultValue);
... I know it is possible to cast to HashMap everytime, but is there a better way?
}
public HashMap getResults() {
return results;
}
You could use generics to achieve this:
Here I used key and value types of
StringandIntegeras examples. You could also makeChildgeneric on the key and value types if they vary:If you’re wondering how to initialize the
resultsfield, that could take place in the constructor for example:Some side notes:
It would be better for encapsulation if you made the
resultsfieldprivate, especially since it has the accessorgetResults()anyway. Also, consider making itfinalif it’s not going to be reassigned.Also, I’d recommend programming to interface by using the
Maptype in your public declarations rather thanHashMapspecifically. Only reference the implementation type (HashMapin this case) when it’s instantiated: