Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need clarification about inheritance and exceptions

Tags:

java

oop

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?

like image 472
whoadiz Avatar asked Jul 12 '12 19:07

whoadiz


1 Answers

Vehicle has a drive() method that throws an exception.

Car overrides the Vehicle's Drive() method with it's own Drive() method which does not throw an exception.

The reason you get the output that you do is because even though Vehicle v is of type car, the compiler doesn't know that fact at compile time, so when you call v.drive() the compiler doesn't know that you're calling Car's drive method.

Let's say that you instantiated v in the following way:

Vehicle v;
if(rand(0,1) == 1)
    v = new Car();
else
    v = new Vehicle();

You wouldn't know whether or not v is a car when you compile. You wouldn't know until you run the program.

like image 120
Sam I am says Reinstate Monica Avatar answered Nov 02 '22 09:11

Sam I am says Reinstate Monica