我假设你的代码是这样的?
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