简体   繁体   中英

Forcing subclasses of my class to override only certain functions in Java

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 .

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:

@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:

  1. You can declare a method (and the base class) abstract . Concrete classes will be forced to implement the method.
  2. Declare non-overrideable methods final . Derived classes cannot override these methods.
  3. Combine 1 & 2: declare a method final and have it delegate part of its work to an abstract method. (This pattern is often used with an empty method instead of an abstract method to implement so-called "hooks" into otherwise fixed logic.)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM