如何正确调用抽象 class 中的方法

How to call a method in an abstract class properly

public abstract class Human{
    public String name;
    public int number

    public void getInfo(){
        Name = JOptionPane.showInputDialog("Please enter your name: ");
        money = Double.parseDouble(JOptionPane.showInputDialog("Please enter amount of money .00: "));
    }

    public void displayInfo(){
        JOptionPane.showMessageDialog(null,"Name: "+name+"\n"+
                                           "Number: "+number);
    }
}

public class Student extends Human {

}

public class Teacher extends Human{

}

public class Janitor extends Human{

{

如果在下面的所有 3 class 中调用方法 getInfo() 和 displayInfo(),我需要帮助。我试过:

public class Student extends Human{
    public Student(){
          getInfo();
          displayInfo();
    }

它有效,但它会生成一条警告,提示“构造函数中的调用有问题”,我想这不是最好的方法。

我也试过:

@Override
public void getInfo() {
    
}

但如果我将其留空,则什么也不会发生。基本上我试图以一种简单的方式调用抽象 class 中的方法,而不需要在每个 class.

中键入它

您收到警告是因为良好做法 不要在构造函数中调用 overridables;因为这些 overridable 可能会尝试访问 尚未初始化的成员变量 (== null) .

您不应在构造函数中调用可重写的函数。检查这个 link

如前所述,您不应在构造函数中调用可重写的方法,因为如果另一个 class 重写此方法并调用 superclass 的构造函数,它可能会尝试使用以下值尚未初始化,因为将调用覆盖的方法。示例:

public class Superclass {
  protected int id;
  protected void foo() {
    System.out.println("Foo in superclass");
  }

  public Superclass() {
    foo();
  }
}

public class Subclass extends Superclass {
  public Subclass(int id) {
    super();
    this.id = id;
  }

  @Override
  protected void foo() {
    System.out.println("Id is " + id);
  }
}

这将打印 id 的单元化值,因为您首先调用了 superclass 的构造函数,它调用了 sub[ 的 foo 方法=22=].

如果适合您的情况,您可以通过制作您的方法 final 来解决此问题。