I have a Base class with a method that a child class will almost always override. However, instead of replacing the base class’ method entirely, I would like for whatever is derived in the child class to be added to what is already in the base class.
For Example:
class BaseClass{
public string str()
{
return "Hello my name is" ;
}
}
class ChildClass : BaseClass{
public override string str()
{
return "Sam";
}
}
The point is that if I want to access the str() method by creating an instance of the ChildClass, the string will print out as “Hello, my name is Sam”.
I’ve been looking around and all I have been finding is that this should NOT happen, as the base class shouldn’t even know that it is being inherited. So, if the design is false, how would I go about doing this? Keep in mind that there will be multiple child classes inheriting from BaseClass.
Thank you
If you always want to do this, and you don’t want to rely on implementers of the derived classes to remember to override the method and call into the base class, you can use a template pattern:
Now any non-abstract class that inherits
BaseClasswill be required by the compiler to overrideName, and that value can be consumed byBaseClass.Obviously, this depends on the base class being
abstract.