我想知道为什么的Java:重载方法
z.f(-6);
在M级的呼叫是指下列函数B类:的
public void f(double y) {
this.x = (int) y + B.y;
}
,而不是在A级使用函数f,因为bx由A覆盖。或者使用
public void f (int y) {
this.x = y*2;
B.y = this.x;
}
在类B中,至少参数类型匹配。
完成以下代码:
public class A {
public int x = 1;
public A(int x) {
this.x += x;
}
public A (double x) {
x += x;
}
public void f(double x) {
this.x = this.x + (int) (x + B.y);
}
}
public class B extends A {
public static int y = 3;
public int x = 0;
public B (double x) {
super((int) x);
}
public void f(int y) {
this.x = y*2;
B.y = this.x;
}
public void f(double y) {
this.x = (int) y + B.y;
}
}
public class M {
public static void main (String[] args){
A a = new A(B.y);
a.f(1);
B b = new B(3.0);
A z = b;
z.f(-5.0);
z.f(-6);
System.out.println(b.x + " " + z.x);
}
}
我觉得Mike Samuel的回答很好,因为z有类型A,尽管它拥有A的一个子类B的实例,但只有A的方法可以被调用;对于子类型B的方法的调用,你将不得不downcast z(尽管使用checked downcast,例如使用instanceof,因为否则可能会遇到运行时异常)。 - 在一个不相干的笔记上,既然我看到了你对理论计算机科学的简介,并且正在考虑在RWTH做我的主人,那么在那里学习怎么样?从您对TCS的问题来看,听起来有些苛刻? – 2012-03-13 23:51:48
编辑:我误读了麦克塞缪尔的答案,在他的第一句话,它需要阅读“A.f(双)”。一个正确的,不太详细的答案(这也是不太需要,而仍然捕捉问题)将是悲惨变量的;也检查那一条的评论。 – 2012-03-14 00:33:56
@ G. Bach:我可以强烈推荐RWTH大学。这很有挑战性,但很有趣。我只是在我的第一个学期,所以我的经验是相当有限的;-) – Laura 2012-03-15 18:46:09