gpt4 book ai didi

java - 方法重载练习

转载 作者:行者123 更新时间:2023-12-02 15:18:04 24 4
gpt4 key购买 nike

我在考试中得到了这个练习,但我想不出 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 的调用在 Xh 中:

return f(b,n);

如果您查看 X,它唯一可以调用的 f 就是它的 f(A, int)。它无权访问 f(B, int)。所以它是通过调用 f(A, int) 来编译的。 Y 会覆盖 f(A, int)Z 不会,因此任何 Y 实例(包括Z 实例)将使用 Yf(A, int) 版本。所以 Yf(A, int) 被使用了。

关于java - 方法重载练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39189740/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com