Need to clarify inheritance and exceptions

So, I'm trying to understand why the program compiles the way it is, I hope you guys can explain it to 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()
   }
}

Thus, the output for the above program will be

Car start car start car start

My question is: why should I do a try / catch block to call the drive () method on v and c2 objects but not c? They are all vehicle instances, so what happens here?

+5
source share
4 answers

Vehiclehas a method drive()that throws an exception.

Caroverrides a method Vehicle drive()using its own method drive(), which does not throw an exception.

, , , , Vehicle v , , , v.drive(), , Car drive.

, v :

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

, v . , .

+10

, . , . (() ()). Drive(), , , , Vehicle.

+1

:

  Vehicle v = new Car();
  Car c = new Car();
  Vehicle c2 = (Vehicle) v;

v c2 Vehicle. , public void drive() throws Exception Vehicle. try/catch , c.drive() ( ).

0

; . , :

, ?

Car - :

  Vehicle v = new Car();
  Car c = new Car();
  Vehicle c2 = (Vehicle) v;

At compile time, it is vconsidered how Vehicle, chow Car, and the corresponding exceptions will be handled accordingly. At run time, the JVM knows what vit actually contains Car, but is different.

0
source

All Articles