有没有办法制作一个不是抽象但必须被覆盖的方法?

有没有办法强制子类覆盖超类的非抽象方法?

我需要能够创建父类的实例,但是如果一个类扩展了这个类,它必须给出自己的某些方法的定义。


答案 1

据我所知,没有直接编译器强制的方法可以做到这一点。

您可以通过使父类可实例化,而是提供一个工厂方法来解决这个问题,该方法创建具有默认实现的某些(可能的私有)子类的实例:

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
    }
  }
}

您现在无法编写,但可以执行操作以获取默认实现。new Base()Base.create()


答案 2

正如其他人所指出的那样,你不能直接这样做。

但要做到这一点,一种方法是使用 Strategy 模式,如下所示:

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
        }
    }
}

推荐