Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java method overriding and variable shadowing

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).

like image 941
The Wizard Avatar asked Sep 15 '14 11:09

The Wizard


1 Answers

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.

like image 59
Michał Kosmulski Avatar answered Sep 20 '22 23:09

Michał Kosmulski