raj_n
raj_n

Reputation: 186

Which approach is better in terms of Object Oriented Programming?

Superclass -> Vehicle | Subclasses -> Car & Bike

If the class Car requires a startCar() method (which outputs a string of value 'BRUMM' when invoked) and even the class Bike requires a similar method startBike() (which outputs a string of value 'TRUMM' when invoked) Would it be better to go about it this way, or instead have a startVehicle() method in the superclass Vehicle which is coded differently for the different outputs for the respective subclasses: Car and Bike?

Edit: Bike refers to Motor Bike

Upvotes: 0

Views: 102

Answers (1)

jonathanl
jonathanl

Reputation: 524

First, instead of using startCar() and startBike() [and startVehicle()] respectively, the function could [and should] just be called 'start()' (e.g. Car.start(), Bike.start(), Vehicle.start()), as each function shares the same intention, and is designed to give the same type of output.

Now, if most/all of your subclasses are going to implement a start function then I'd recommend creating the start() function in the superclass, and then overriding it in the subclasses.

Additionally, if Car.start() and Bike.start() share a lot (but not all) of the same functionality (e.g. they both start an engine of some sort), then put the similar code into the Vehicle.start(). Then, when you write Car.start() and Bike.start() to override Vehicle.start(), the respective functions should call Vehicle.start() method, before running their class-specific code.

P.S. Definitely do not code the superclass's start() function to put out a different value based on a class's actual type; basically a superclass shouldn't have to know about the subclass... otherwise, what's the point? :)

Upvotes: 4

Related Questions