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());
}
}
Hi, I am having trouble understanding the output of the code above. The output is:
Radius = 10.0
Radius = 10.0
Radius = 100.0
Radius = 10.0
I understand why gc.r is 10. I also understand why gc.getR() is 10 (because the getR() method in the GraphicCircle overrides the getR() method of Circle). But I don't understand why c.r is 100, and c.getR() is 10 (I am having trouble understanding what happens in inheritance when you typecast to an ancestor class as the code has done above).