我是Java初學者。 任何人都可以解釋爲什麼它打印輸出2?Java程序的輸出
interface Foo {
int bar();
}
public class Beta {
class A implements Foo {
public int bar() {
return 1;
}
}
public int fubar(final Foo foo) {
return foo.bar();
}
public void testFoo()// 2
{
class A implements Foo {
public int bar() {
return 2;
}
}
System.out.println(fubar(new A()));
}
public static void main(String[] args) {
new Beta().testFoo();
}
}
我認爲可能是由於對「new A()」的調用發生在testFoo()方法而不是fubar()的上下文中而引起混淆。 – 2011-05-03 15:25:41
+1,快速正確迴應。但@Neal,我喜歡避免使用「重新定義」這個術語,因爲在其他一些語言中,您實際上可以重新定義方法本身。我喜歡「隱藏」一詞。思考? – 2011-05-03 15:28:56
@Dumum,是的,但是如何在這種情況下放置'hide'? – Neal 2011-05-03 15:29:30