OCR code
namespace Example027
{
class Program
{
static void Main(string[] args)
{
Vehicle v = new Truck();
v.Run();
}
}
abstract class Vehicle
{
public void Stop()
{
Console.WriteLine("Stopped!");
}
public void Fill()
{
Console.WriteLine(" Pay and fill...");
}
public abstract void Run();
}
class Car : Vehicle
{
public override void Run()
{
Console.WriteLine("Car is running ...");
}
}
class Truck : Vehicle { }
}
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()
I don't understand the necessity of using abstract classes?
A problem with your idea is that it lacks abstraction. You could not write a method like
public static void FillAndRun(Vehicle vehicle){
vehicle.Fill(); // Fine
vehicle.Run(); // Not fine, No such method on Vehicle
}
You could make a virtual run-method. But then you have the problem how the base class should implement it. An abstract class provides a common interface, and forced each derived class to implement its own run-method.
But dividing your code into reusable components is hard, and an abstract class may not be the best way to do it.
One problem with abstract classes is that it mixes two related, but different concepts. Interface Inheritance and implementation inheritance.
Interface inheritance is used to provide a common interface for the users of the class, and is typically done with an interface. This is common and perfectly fine if used correctly.
Implementation inheritance is done to reuse an implementation, and this is more problematic. You can only inherit from one class, so if you want to reuse implementations from multiple classes you are out of luck. There is also the fragile base class problem and many other potential issues. Because of this it is usually recommended to prefer 'composition over inheritance', i.e. move common implementations to other classes or static methods for re-use.
It is also somewhat common for new developers to over use inheritance, and this often results in 'Leaky abstractions'. So for a new developer I would suggest not to worry to much about open/closed, abstraction, interfaces etc. It is a really difficult topic that even experienced developers struggle with.