简体   繁体   English

在Java中,如何在继承的类中覆盖变量的类类型?

[英]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? 在Java中,如何在继承的类中覆盖变量的类类型? 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: 您可以使用泛型来实现此目的:

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. 在这里,我以StringInteger键和值类型为例。 You could also make Child generic on the key and value types if they vary: 如果键和值类型有所不同,也可以使Child通用:

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: 如果您想知道如何初始化results字段,可以在构造函数中进行以下示例:

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. 如果将results字段设置为private ,则对于封装会更好,特别是因为它无论如何都具有访问器getResults() Also, consider making it final if it's not going to be reassigned. 另外,可以考虑将其final ,如果它不会被重新分配。

Also, I'd recommend programming to interface by using the Map type in your public declarations rather than HashMap specifically. 另外,我建议您通过在公共声明中使用Map类型进行编程以进行接口连接 ,而不是专门使用HashMap Only reference the implementation type ( HashMap in this case) when it's instantiated: 实例化时仅引用实现类型(在这种情况下为HashMap ):

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

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

    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM