最近我偶然发现了 Java 测试并发现了一个奇怪的行为。
class MainOne {
private int i = 5;
public MainOne() {
System.out.println("MainOne says that I is " + getI());
}
public int getI() {
System.out.println("MainOne getI was used");
return i;
}
}
public class TheTest extends MainOne {
private static int i = 10;
public TheTest() {
System.out.println("TheTest says that I is " + super.getI());
}
public int getI() {
System.out.println("TheTest getI was used");
return i;
}
public static void main(String[] args) {
TheTest test = new TheTest();
}
}
结果是:
使用了Test getI
MainOne 说我是 10 岁。
MainOne getI 被使用
TheTest 说我是 5
问题是,发生了什么?基类如何使用它的后代方法?