带有 body 的 Java “abstract like” 方法

2022-09-04 06:54:49

有以下类:

public abstract class Super
{
    public abstract void run();
}

public class Sub1 extends Super
{
    @Override
    public void run ()
    {
        System.out.println("Method called");
        System.out.println("Sub1 called");
    }
}

public class Sub2 extends Super
{
    @Override
    public void run ()
    {
        System.out.println("Method called");
        System.out.println("Sub2 called");
    }
}

我怎样才能避免我必须写两次“System.out.println(”Method called“);”?

感谢您的回答

CalibeR.50


答案 1

将公共功能引入超类,并定义另一个抽象方法,子类将为其定义自己的实现。

public abstract class Super {
    public void run() {
        System.out.println("Method called");
        printMessage();
    }
    abstract void printMessage ();
}

public class Sub1 extends Super {
    @Override
    void printMessage() {
        System.out.println("Sub1 called");
    }
}

public class Sub2 extends Super {
    @Override
    void printMessage () {
        System.out.println("Sub2 called");
    }
}

通过这种方式,您可以避免重复调用超类的通用方法两次。


答案 2

您可以将 run() 实现放入抽象类中:

// Super is still an abstract class
public abstract class Super
{
    // While method run is not an abstract method:
    public void run() 
    {
        System.out.println("Method called");
    }
}

public class Sub1 extends Super
{
  // There's no need of declaring run() here unless you want to change its behaviour
}

public class Sub2 extends Super
{
}

在问题的已编辑版本中,只能使用继承的运行实现

// Super is still abstract
public abstract class Super
{
    // But method run is not abstract
    public void run() 
    {
        System.out.println("Method called");
    }
}

public class Sub1 extends Super
{
  @Override
  public void run()
  {
      super.run(); // <- call Super.run() that prints "Method called"
      System.out.println("Sub1 called");
  }
}

public class Sub2 extends Super
{
  @Override
  public void run()
  {
      super.run();
      System.out.println("Sub2 called");
  }
}

推荐