I want to force subclass to implement an implemented method of my mother class. I look this Java - Force implementation of an implemented method but i can't convert my mother class to an abstract class.
public class myMotherClass {
myMethod {
...some code ..
}
}
public class myClass extends myMotherClass {
myMethod {
... other code ...
}
}
So, in this exemple, I want to force myClass implement myMethod.
Sorry for my english...
You could rework your hierarchy so that your concrete classes are only leafs of the tree.
Instead of
Consider
This way the Abstract class is inherited by both instantiated classes. It is likely in this case the
myMotherClass
would be extremely thin, just the implementation ofmyMethod
.If you really want to force to implement method use should use
interface
.Now if some one want to implement from this interface as
MyClass implements MyInterface
, You have to implementmyMethod();
You can not force a subclass to override a method. You can only force it to implement a method by making it abstract.
So if you can not make myMotherClass abstract you can only introduce another superclass that extends myMotherClass and delegates to the method that must be implemented:
EDIT
I found another interessting way of solving the problem in the
hemcrest
api that is e.g. used by mockito.The interface specifies a method
_dont_implement_Matcher___instead_extend_BaseMatcher_
. Of course it does not prevent others from implementing theMatcher
interface, but it guides the developer in the right direction.And the
BaseMatcher
class implements the_dont_implement_Matcher___instead_extend_BaseMatcher_
method as finalFinally I think that this is a design problem, because the
BaseMatcher
obviouosly implements logic that everyMatcher
should implement. Thus it would have been better to make theMatcher
an abstract class and use a template method.But I guess they did it because it was the best compromise between bytecode compatibility and new features.
One thing most people are overlooking is the following implementation (although I saw mention of it in a comment):
In most cases this should be enough, as you should have some form of acceptance testing (even if it is only testing the inheriting class by hand). In theory, you are still introducing the possibility that nobody will realize that the method hasn't been overwitten until production though.