-1

If I have a superclass named Vehicle and a subclass named SportsCar, what is the difference between these 2 codes to create an object of SportsCar? What would be the difference between car1 vs car2?

SportsCar car1 = new SportsCar();
Vehicle car2 = new SportsCar();

1 Answers1

1

I will explain it to you through an example:

Assume you had another subclass of Vehicle named SUV. Now, if you were to write a function that refuels vehicles. Since refueling remains the same for SportsCar and SUV you can have a function like :

void refuel(Vehicle vehicle){
   vehicle.refuel = true;
}

With the initialization like Vehicle car1 = new SportsCar();, and Vehicle car1 = new SUV();, you could easily call the function refuel(car1); refuel(car2);

The reason is simple, a parent class is a common reference for the various subclasses.

You can also have a look at this common scenario in the java world!!

You can also go through this to understand the technicality of why it works in that way. And how is it an important pillar of OOP.

paradocslover
  • 2,932
  • 3
  • 18
  • 44