I understand how the following code works, based on polymorphism and dynamic binding. Java is somehow able to figure out at runtime that because vh is a MotorBike, we should call MotorBike's move() method.
class Vehicle{
public void move(){
System.out.println(“Vehicles can move!!”);
}
}
class MotorBike extends Vehicle{
public void move(){
System.out.println(“MotorBike can move and accelerate too!!”);
}
}
class Test{
public static void main(String[] args){
Vehicle vh=new MotorBike();
vh.move(); // prints MotorBike can move and accelerate too!!
}
}
What I don't understand is why the following code breaks. the only change I've made is to delete the move() method from the Vehicle class. Now I get a compile error that says "cannot find symbol - method move()". Why is this so? Why does the previous example work and this code doesn't?
class Vehicle{
}
class MotorBike extends Vehicle{
public void move(){
System.out.println(“MotorBike can move and accelerate too!!”);
}
}
class Test{
public static void main(String[] args){
Vehicle vh=new MotorBike();
vh.move(); // compile error
}
}