So I am trying to figure out why a program is compiling the way it is, hopefully you guys can explain it for me.
class Vehicle{
public void drive() throws Exception{
System.out.println("Vehicle running");
}
}
class Car extends Vehicle{
public void drive(){
System.out.println("Car Running");
}
public static void main(String[] args){
Vehicle v = new Car();
Car c = new Car();
Vehicle c2 = (Vehicle) v;
c.drive();
try {
v.drive();
} catch (Exception e) {
e.printStackTrace();
} //try v.drive()
try {
c2.drive();
} catch (Exception e) {
e.printStackTrace();
} //try c2.drive()
}
}
So the output for the above program is going to be
Car Running
Car Running
Car Running
My question is, why do I have to do a try/catch block to call drive() method for the v and c2 objects but not the c? They are all instance of Car so what’s happening here?
Vehiclehas adrive()method that throws an exception.Caroverrides theVehicle‘sDrive()method with it’s ownDrive()method which does not throw an exception.The reason you get the output that you do is because even though
Vehicle vis of type car, the compiler doesn’t know that fact at compile time, so when you callv.drive()the compiler doesn’t know that you’re calling Car’sdrivemethod.Let’s say that you instantiated
vin the following way:You wouldn’t know whether or not v is a car when you compile. You wouldn’t know until you run the program.