I want to implement a function in the base class but I also want it to be overridden in the derived classes every time. So it is more like "abstract function but with a body".
What am I looking for? Am I looking for the right thing?
A subclass must override all abstract methods of an abstract class. However, if the subclass is declared abstract, it's not mandatory to override abstract methods.
If you don't, a compile time error will be generated for each abstract method (that you don't override) saying “subclass_name is not abstract and does not override abstract method abstractmethod_name in classname”.
In Java, it is compulsory to override abstract methods of the parent class in its child class because the derived class extends the abstract methods of the base class. If we do not override the abstract methods in the subclasses then there will be a compilation error.
All the abstract methods should be overridden in the child class to provide the implementation. However, from the definition, a final method can't be overridden. Therefore, an abstract final combination is illegal for the methods.
If the base-class has something to say, but you want it overridden "every time", then I would have a pair of methods:
public void DoSomething() {
//things to do before
DoSomethingCore();
//things to do after
}
protected abstract void DoSomethingCore();
If your base class does something in the method, but you want to make sure that every subclass is forced to implement some part of the method, then you want the Template Method pattern, as described in Marc Gravell's answer.
There's no way to provide a default implementation in your base class and still force subclasses to provide their own implementation. You could however create an abstract base class and inherit from it to provide the default implementation, but make that concrete class sealed.
public abstract class FooBase {
public abstract void DoStuff();
}
public sealed class FooImpl : FooBase {
public override void DoStuff {
//default widget-munging code
}
}
Now any classes which inherit from FooBase have to implement DoStuff(), but you have a default implementation FooImpl from which subclasses may not inherit.
You might also prefer to delegate the responsibility for implementing the method to a separate class, which is passed to the base class in its constructor. That's called the Strategy pattern.
public sealed class Foo {
private IFooStrategy _strategy;
public Foo(IStrategy strategy) {
_strategy = strategy;
}
void DoStuff() {
_strategy.DoStuff();
}
public static IFooStrategy DefaultStrategy {
//return singleton instance of the default strategy
}
}
Now instead of subclassing Foo, you instead create new implementations of the IFooStrategy interface, and pass those to your Foo instance. So you could either do:
new Foo(Foo.DefaultStrategy);
or
new Foo(new DifferentStrategy());
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