【发布时间】:2014-06-01 11:08:41
【问题描述】:
所以,一个朋友给我发了这段代码,说编译成功,返回 42。 但是,麻烦的是“返回” 42 的父类中的方法是私有的,而被调用的方法是在子类中的,它是公共的。那么,谁能说出这是为什么以及如何工作的?
static class A {
private int f() {
return 42;
}
}
static class B extends A {
public int f2() {
return super.f();
}
}
public static void main(String[] args) {
System.out.print(new B().f2());
}
它返回 42。
我试图摆脱静电,并且
class A {
private int f() {
return 42;
}
}
class B extends A {
public int f2() {
return super.f();
}
}
public static void main(String[] args) {
Main m= new Main();
B b= m.new B();
System.out.print(b.f2());
}
它仍然返回 42。
【问题讨论】:
标签: java inheritance private public