I am confused: I have taken the following quotes (with the titles of the sections in which they appear) from a learning resource, but the quotes seem to me to contradict each other.
"it is the type of the reference variable-not the type of the object that it refers to-that determines what members can be accessed"
"it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed"
Any clarification on this would be appreciated.
Suppose we have two classes.
class Vehicle{
    
    public void drive(){
        System.out.println("Vehicle is Moving");
    }
}
class Car extends Vehicle{
    
    public void drive(){
        System.out.println("Car is Moving");
    }
    
    public void playMusic(){
        System.out.println("Car is Playing Music");
    }
}
"it is the type of the reference variable-not the type of the object that it refers to-that determines what members can be accessed"
It means if we have a code like
Vehicle vehicle = new Car();
Using vehicle object, we can call drive(), but not playMusic(), Because type of vehicle is Vehicle.
"it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed"
It means if we have a code like
Vehicle vehicle = new Car();
vehicle.drive();
It will print "Car is Moving" not "Vehicle is Moving", becasue the object stored in vehicle is an instance of Car.
Have a look at below program.
class SuperMem{
    int i = 90;
    int j = 100;
    void show(){
        System.out.println("parent show..");
        System.out.println("Show inside Parent start");
        System.out.println(i + " " + j);
        System.out.println("Show inside Parent END");
    }
}
class submem extends SuperMem{
    int i = 10;
    int j = 20;
    void show(){
        System.out.println("Child show ..");
        System.out.println("Show inside Child start");
        System.out.println(i + " " + j);
        System.out.println("Show inside Child END");
    }
}
public class SuperMemDemo {
    public static void main(String[] args) {
        SuperMem m = new SuperMem();
        submem s = new submem();
        m = s;
        System.out.println("i " + m.i);
        System.out.println("j " + m.j);
        m.show();
    }
}
Output:
   i 90
   j 100
   Child show ..
   Show inside Child start
   10 20
   Show inside Child END
Methods are resolved via dynamic dispatch methods i.e. at runtime. Analyse output and you will get meaning of above two statements from Complete reference Herbert Schildt
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