OOD - why car/bus/motocycle should derive from vehicle

276 Views Asked by At

Suppose we design a parking lot class. There are two ways to define the vehicles.

1)

Abstract class Vehicle {
        protected int size;
        private string plate;
        ...
}
class car : Vehicle{
     car(){base.size = enum.carSize;} 
 }
class bus: Vehicle{
     bus(){base.size = enum.busSize;} 
 }

2)

class Vehicle {
        private int size;
        protected string plate;
        public setSize(int size);
}

Then in parking lot class we can define

       Vehicle Car;
       vehicle Bus;

Which one is better? I see 1) is used in "cracking the coding interview". But I see 2) is better as it is simple. What should I use in interview?

2

There are 2 best solutions below

0
On

If you do not need different kinds of functionalty for different kinds of Vehicle you dont need inheritance.

0
On

Your Vehicle class has base methods and attributes, like engine(), licensePlate = '' and so on. All vehicles will have these methods and attributes.
Now Car and Bus class is different from each other, so you extend Vehicle class within Car and Bus classes to have same base functionality, but to be different in specific functionality (like Car can have stereoType = '' while Bus can have hasSecondFloor = true.

class Vehicle {
    private $licensePlate;
    public function startEngine()
    {
        /* ... */
    }

    public setLicensePlate()
    {
        /* ... */
    }
}

class Car extends Vehicle {
    public function _construct()
    {
       $this->setLicensePlate('ABC-123');
       $this->startEngine();
    }

    public function turnOnStereo()
    {
        /* ... */
    }
}