方法覆盖
yjava 2004-03-09 10:11:43 class Homer {
char doh(char c) {
System.out.println("doh(char)");
return 'd';
}
float doh(float f) {
System.out.println("doh(float)");
return 1.0f;
}
}
class Milhouse {}
class Bart extends Homer {
void doh(Milhouse m) {}
}
}
class Hide {
public static void main(String[] args) {
Bart b = new Bart();
b.doh(1); // doh(float) used
b.doh('x');
b.doh(1.0f);
b.doh(new Milhouse());
}
如果把float doh(float f)写在Bart中,既
class Homer {
char doh(char c) {
System.out.println("doh(char)");
return 'd';
}
float doh(float f) {
System.out.println("doh(float)");
return 1.0f;
}
}
class Milhouse {}
class Bart extends Homer {
void doh(Milhouse m) {}
float doh(float f) {
System.out.println("doh(float)");
return 1.0f;
}
}
class Hide {
public static void main(String[] args) {
Bart b = new Bart();
b.doh(1); // doh(float) used
b.doh('x');
b.doh(1.0f);
b.doh(new Milhouse());
}
再编译时b.doh('x');就有问题了,
Hide.java:31: reference to doh is ambiguous, both method doh(char) in Homer and
method doh(float) in Bart match
b.doh('x');
^
不明白为什么会这样,我认为,Bart extends Homer,完全复写一个方法有什么不对,不复写能运行!