2012-09-04 34 views
0

在Java中,如何覆蓋繼承類中變量的類類型?例如:在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; 
} 
+0

而不是'Object',你不能用'Map'返回類型? – Sujay

回答

8

你可以使用generics來實現這一目標:

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(); 
     ... 
    } 
} 

這裏我用的StringInteger鍵和值類型作爲例子。你也可以將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>()); 
    } 

    ... 
} 

一些旁註:

這將是encapsulation更好,如果你做的resultsprivate,尤其是因爲它無論如何都有訪問者getResults()。另外,如果它不會被重新分配,請考慮將其設爲final

此外,我會推薦programming to interface在您的公開聲明中使用Map類型,而不是HashMap。僅供參考(在這種情況下HashMap)實現的類型時,它的實例:

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

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

    ... 
}