[英]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.