Imagine I have a class called Engine as an abstract base class. I also have ElectrictEngine and FuelEngine classes which derive from it.
I want to create a method for refueling the engine. Should I do it as an abstract method on the base class level and name it in a generic fasion, such as fillUpEnergy?
The problem is that if I have an electric engine, the number of parameters which the method takes is different from the number of parameters which need to be passed for a Fuel Engine. So, the method's signature is different.
In addition, is there any smart way to use the generic method for both engines but to wrap it in a more specific name? For example: for a fuel Engine, "refuel", and for an electric engine, "chargeBattery"? And at the same time hide the generic method from the user?
Abstract Classes and Methods Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class). Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).
A non-abstract child class of an abstract parent class must override each of the abstract methods of its parent. A non-abstract child must override each abstract method inherited from its parent by defining a method with the same signature and same return type. Objects of the child class will include this method.
Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract .
It is necessary to override all the methods which are declared as abstract . you cannot skip the non-concrete methods. If you really want to do then make your class as abstract.
In this situation, I would define a generic implementation of your abstract class, such that you get something like this:
public abstract class EngineBase<T>
{
public abstract void Refuel(T parameters);
}
Then your implementations look like this:
public class ElectricEngine : EngineBase<ElectricParameters>
{
public override void Refuel(ElectricParameters parameters) { }
}
Alternatively, you can define an interface, and pass a specific implementation to your methods:
public abstract class EngineBase
{
public abstract void Refuel(IRefuelParameters parameters);
}
Then your implementations look like this:
public class ElectricEngine : EngineBase
{
public override void Refuel(IRefuelParameters parameters)
{
if(!(parameters is ElectricParameters))
throw ApplicationException("Not the right params!");
ElectricParameters rightParams = parameters as ElectricParameters;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With