Is there a way to make a method which is not abstract but must be overridden?
Is there any way of forcing child classes to override a non-abstract method of super class?
I need to be able to create instances of parent class, but if a class extends this class, it must give its own definition of some methods.
Solution 1:
There is no direct compiler-enforced way to do this, as far as I know.
You could work around it by not making the parent class instantiable, but instead providing a factory method that creates an instance of some (possible private) subclass that has the default implementation:
public abstract class Base {
public static Base create() {
return new DefaultBase();
}
public abstract void frobnicate();
static class DefaultBase extends Base {
public void frobnicate() {
// default frobnication implementation
}
}
}
You can't write new Base()
now, but you can do Base.create()
to get the default implementation.
Solution 2:
As others have pointed out, you can't do this directly.
But one way to do this is to use the Strategy pattern, like so:
public class Base {
private final Strategy impl;
// Public factory method uses DefaultStrategy
// You could also use a public constructor here, but then subclasses would
// be able to use that public constructor instead of the protected one
public static Base newInstance() {
return new Base(new DefaultStrategy());
}
// Subclasses must provide a Strategy implementation
protected Base(Strategy impl) {
this.impl = impl;
}
// Method is final: subclasses can "override" by providing a different
// implementation of the Strategy interface
public final void foo() {
impl.foo();
}
// A subclass must provide an object that implements this interface
public interface Strategy {
void foo();
}
// This implementation is private, so subclasses cannot access it
// It could also be made protected if you prefer
private static DefaultStrategy implements Strategy {
@Override
public void foo() {
// Default foo() implementation goes here
}
}
}
Solution 3:
Consider making an interface with this method. Class descendants will have to implement it.
Solution 4:
I think the easiest way is to create an abstract class that inherits from the base class:
public class Base {
public void foo() {
// original method
}
}
abstract class BaseToInheritFrom extends Base {
@Override
public abstract void foo();
}
class RealBaseImpl extends BaseToInheritFrom {
@Override
public void foo() {
// real impl
}
}
Solution 5:
No, that's the whole point of an abstract method. What is your use case? Perhaps we can think about it based on the underlying need.