[英]How do I override the variable that was given a value to in another class which has been inherited
[英]In Java, how do I override the class type of a variable in an inherited class?
在Java中,如何在继承的类中覆盖变量的类类型? 例如:
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;
}
您可以使用泛型来实现此目的:
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();
...
}
}
在这里,我以String
和Integer
键和值类型为例。 如果键和值类型有所不同,也可以使Child
通用:
class Child<K, V> extends Parent<HashMap<K, V>> { ... }
如果您想知道如何初始化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>());
}
...
}
一些注意事项:
如果将results
字段设置为private
,则对于封装会更好,特别是因为它无论如何都具有访问器getResults()
。 另外,可以考虑将其final
,如果它不会被重新分配。
另外,我建议您通过在公共声明中使用Map
类型进行编程以进行接口连接 ,而不是专门使用HashMap
。 实例化时仅引用实现类型(在这种情况下为HashMap
):
class Child<K, V> extends Parent<Map<K, V>> {
Child() {
super(new HashMap<K, V>());
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.