I have a class, let’s say
public class GeneralClass<T> {
methodA() {...}
methodB() {...}
methodC() {...}
}
and I’m deriving from this class
public class MoreSpecificClassString extends GeneralClass<String> {
methodD() {...}
methodE() {...}
methodF() {...}
}
public class MoreSpecificClassInt extends GeneralClass<Integer> {
methodX() {...}
methodY() {...}
methodZ() {...}
}
Now, what I would like to know if it is possible to force the subclasses of GeneralClass to override only one method, such as methodA?
Thanks
Yes. Make
methodAabstract and makeGeneralClassan abstract class. If you want to prohibit overridingmethodBandmethodC, mark them asfinal.Edit
If on the other hand you want to be able to provide a default implementation of
methodA, and also require subclasses to override it, you are essentially violating the Liskov Substitution Principle. You need to reevaluate why you require this design, because it smells pretty bad. For example, there would be absolutely nothing preventing your subclass from just overriding your method like this:And if the re-implementation can just call the super class’ default implementation, what was the point in forcing it to be overridden in the first place?
It’s for this reason (among others) that it’s not possible to provide a default implementation and require subclasses to override it. Rethink your design.