我假設你的代碼是這樣的?
class Element {
public Element manipulate(Element e) { ... }
}
class Graph extends Element {
@Override
public Graph manipulate(Graph g) { ... }
}
這會給你一個錯誤。我認爲它不能被允許的理由是這樣的:
Graph g1;
Element e1 = g1;
Vector v1; // another subclass of Element
Element e2 = e1.manipulate(v1);
e1
被聲明爲Element
,所以編譯器將允許e1.manipulate(v1)
因爲v1
也是Element
(實際上屬於一個子類,這是OK) 。編譯器在編譯時不知道e1
實際上是Graph
。但是當你運行它時,由於e1
在運行時的實際類型是Graph
,Graph
類中的manipulate
方法被稱爲(多態),但參數g
是Vector
而不是Graph
,如參數g
所述,它應該是是。那麼該計劃應該做什麼?
如果上面真的是你想要的,你需要像
class Graph extends Element {
@Override
public Graph manipulate(Element e) { // it's OK to change the *return* type,
// in later versions of Java
if (e instanceof Graph) {
Graph g = (Graph)e;
// now you can work with g
} else
throw new SomeException(); // or return null, or whatever is
// appropriate
}
}
不知道,如果你的問題是像這樣的東西,因爲我還沒有看到任何的代碼呢。
來源
2013-08-22 19:36:27
ajb
小心給我們看一些代碼? – StormeHawke
你有Graph和Vector作爲Element的子類,putGraph和putVector是Put類的子類嗎?是對的嗎? – Kon
代碼在哪裏,錯誤是什麼? – GriffeyDog