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 methodA
abstract and make GeneralClass
an abstract class. If you want to prohibit overriding methodB
and methodC
, mark them as final
.
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:
@Override
public void methodA() {
super.methodA();
}
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.
Yes, make GeneralClass
an abstract class, with implementations for the other methods.
Example:
abstract class ABC {
abstract int methodA();
final int methodB() { ... implementation ...}
}
仅强制一个-使此方法abstract
吗?
You have several tools available:
abstract
. Concrete classes will be forced to implement the method. final
. Derived classes cannot override these methods.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.