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).
Method calls are virtual in Java, which means that the method from an object's actual type is called, regardless of what type the reference was which you used to access the object. Direct field access on the other hand is not virtual, so which r
you access will depend on the type of the reference through which you reached it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With