如何确保从子类(Java)中的方法在抽象超类中调用某些方法

mar*_*wun 7 java inheritance

我有一个方法,一个抽象的超A级doSomething().A必须实现的子类doSomething(),但每次子类调用时都应该调用一些公共代码doSomething().我知道这可以实现:

public class A {
  public void doSomething() {
    // Things that every sub-class should do 
  }
}

public class B extends A {
  public void doSomething() {
    super.doSomething();
    // Doing class-B-specific stuff here
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,这似乎有三个问题:

  • 方法签名必须匹配,但我可能只希望在子类方法中返回一些东西,而不是在超类中返回
  • 如果我使A.doSomething()抽象,我不能在A中提供(常见)实现.如果我不使它抽象,我不能强迫子类实现它.
  • 如果我使用不同的方法来提供通用功能,我不能强制B.doSomething()调用该常用方法.

有关如何实施这些方法的任何想法?

Mas*_*sim 6

以下怎么样?

public abstract class A {
  protected abstract void __doSomething();

  public void doSomething() {
    // Things that every sub-class should do 
    __doSomething();
  }
}

public class B extends A {
  protected void __doSomething() {
    // Doing class-B-specific stuff here
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

然而,第一个要点并不是那么清楚.如果您想要返回不同的内容,则签名无法匹配.


kac*_*nov 1

添加对 doSomething() 的回调

public class A {
  public void doSomething() {
    // Things that every sub-class should do 
    doSomethingMore()
  }
}

protected abstract void doSomethingMore()
Run Code Online (Sandbox Code Playgroud)

因此所有子类都必须使用附加操作来 ipmelment doSomethingMore() 但外部类将调用 public doSomething()