vendredi 20 octobre 2023

Why is the Open/Closed Principle in software development implemented using abstract classes?

enter image description here

Please look at the code above. The teacher told us that abstract classes can be used as a tool to implement the Open/Closed Principle in software development. The code above is used as an example to illustrate this. The teacher said that common methods for all vehicles, such as Stop and Fill, are encapsulated in the Vehicle class. Different implementations of these methods are achieved in Car and Truck classes through override. I understand this approach, but I don't think it's necessary to use abstract classes. We can achieve the same with regular classes, right?

Set Vehicle as a regular class, implementing only the Stop and Fill methods within it. Then, let Car and Truck inherit from Vehicle and implement their respective Run methods. At the beginning of the program, use

Var v = new Truck()

or

Truck v = new Truck() 

and still be able to use

v.Run()

So, I don't understand the necessity of using abstract classes?

Aucun commentaire:

Enregistrer un commentaire