【发布时间】:2014-09-15 11:43:10
【问题描述】:
public class Circle {
public float r = 100;
public float getR() {
return r;
}
}
public class GraphicCircle extends Circle {
public float r = 10;
public float getR() {
return r;
}
// Main method
public static void main(String[] args) {
GraphicCircle gc = new GraphicCircle();
Circle c = gc;
System.out.println("Radius = " + gc.r);
System.out.println("Radius = " + gc.getR());
System.out.println("Radius = " + c.r);
System.out.println("Radius = " + c.getR());
}
}
您好,我无法理解上述代码的输出。输出为:
Radius = 10.0
Radius = 10.0
Radius = 100.0
Radius = 10.0
我明白为什么 gc.r 是 10。我也明白为什么 gc.getR() 是 10(因为 GraphicCircle 中的 getR() 方法覆盖了 Circle 的 getR() 方法)。但我不明白为什么 c.r 是 100,而 c.getR() 是 10(当您像上面的代码那样将类型转换为祖先类时,我无法理解继承中会发生什么)。
【问题讨论】:
-
这正是你想知道的——stackoverflow.com/questions/9453701/…
标签: java inheritance