Java 方法重载练习
我考试时做了这个练习,但我想不出一个解决办法。所以我得到了这个:Java 方法重载练习,java,overloading,Java,Overloading,我考试时做了这个练习,但我想不出一个解决办法。所以我得到了这个: 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) {
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)
。这并不简单,但您必须看到类X
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); // <- at this point
} catch(Exception e) {
return n * 4;
}
}
}
Z类不会覆盖公共int f(A,int n)@driescopens:有趣的是,我刚才在想这个问题,然后回来说“但可能不是在这种情况下。”:-)并且记录在案:这个练习的真正教训是:永远不要写这样的代码;-)事实上,为什么有人会编写这样的代码,即使是为了练习。(教授):-)@GhostCat@DriesCoppens练习要点很清楚。它涉及许多概念,如多态性(隐藏与覆盖)和按值调用等。因此,有很多东西值得我们学习;编写一些代码可能需要一些时间。这里的另一个教训是:不要试图回答一个TJ Crowder已经有手指的问题——无论如何,你都太晚了;当你准备发布你的答案时,TJ已经有了一个被接受的答案。@GhostCat你是对的。。。(38秒后):)
public class Y extends X {
public int f(A b, int n) {
return n + b.i();
}
}