我在考试中得到了这个练习,但我想不出 1 个解决方案。所以我得到了这个:
public class X {
public int f(A a, int n) {
n = n + 1;
return 1;
}
public int h(B b, int n) {
try {
n = n + 3;
return f(b,n);
} catch(Exception e) {
return n * 4;
}
}
}
public class Y extends X {
public int f(A b, int n) {
return n + b.i();
}
public int f(B b, int n) {
return 3*n - b.i();
}
}
public class Z extends Y {
public int f(B b, int n) {
return f((A)b,n) + super.f(b,n);
}
}
public class A {
public int i() {
return 7;
}
}
public class B extends A {
public int i() {
return super.i() + 6;
}
}
static class E extends RuntimeException {
}
我需要弄清楚:
new Z().h(new B(), 3)
解法是19 但是我不明白为什么用Y类的f方法而不是Z类的f方法。
最佳答案
被调用方法的签名是在编译时确定的,而不是运行时。对 f
的调用在 X
的 h
中:
return f(b,n);
如果您查看 X
,它唯一可以调用的 f
就是它的 f(A, int)
。它无权访问 f(B, int)
。所以它是通过调用 f(A, int)
来编译的。 Y
会覆盖 f(A, int)
而 Z
不会,因此任何 Y
实例(包括Z
实例)将使用 Y
的 f(A, int)
版本。所以 Y
的 f(A, int)
被使用了。
关于java - 方法重载练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39189740/