ikevin8me
ikevin8me

Reputation: 4313

In Java, how do I override the class type of a variable in an inherited class?

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;
}

Upvotes: 0

Views: 96

Answers (1)

Paul Bellora
Paul Bellora

Reputation: 55213

You could use generics to achieve this:

class Parent<T> {
    protected T results;

    public T getResults() {
        return results;
    } 
}

class Child extends Parent<HashMap<String, Integer>> {

    public void operation() { 
        HashMap<String, Integer> map = getResults();
        ...
    }
}

Here I used key and value types of String and Integer as examples. You could also make Child generic on the key and value types if they vary:

class Child<K, V> extends Parent<HashMap<K, V>> { ... }

If you're wondering how to initialize the results field, that could take place in the constructor for example:

class Parent<T> {

    protected T results;

    Parent(T results) {
        this.results = results;
    }

    ...
}

class Child<K, V> extends Parent<HashMap<K, V>> {

    Child() {
        super(new HashMap<K, V>());
    }

    ...
}

Some side notes:

It would be better for encapsulation if you made the results field private, especially since it has the accessor getResults() anyway. Also, consider making it final if it's not going to be reassigned.

Also, I'd recommend programming to interface by using the Map type in your public declarations rather than HashMap specifically. Only reference the implementation type (HashMap in this case) when it's instantiated:

class Child<K, V> extends Parent<Map<K, V>> {

    Child() {
        super(new HashMap<K, V>());
    }

    ...
}

Upvotes: 8

Related Questions