我是否需要 class 中的每个方法都在子 class 继承的构造函数中?

do I need every method in a class to be in the constructor for subclasses to inherit?

所以,我有这个 class 我制作的,叫做战斗机。我让它工作了一分钟。然后,我添加了这个方法:

private void roll(double block){
    block = (int)(Math.random() * 100);
}

这听起来很愚蠢,但我需要将它添加到构造函数中以继承 class 吗?我想用 subclass

public void attacked(int baseDamage){
  if (human.roll()==block){
     return "Nothing happens";
  }
  else{
     a = human.roll();
     human.health()-= a;
  }
  if (human.health > 0){
     System.out.println(health);
  }

}

那么,我是将 roll() 添加到构造函数中还是有其他方法?

好了回答问题

do I need every method in a class to be in the constructor for subclasses to inherit?

答案是否定的。只需在构造函数中调用您想要的内容即可。如果你想使用 subclass 中的某个方法,那么只需创建一个 class 的实例并调用方法

Object object = new Object("your constructor info"); 
object.newMethod. 

这是你问的吗?

subclass继承了Superclass的所有字段和方法,你可以添加fields/variables和方法来设置它。除了构造函数。

 /* Name of the class has to be "Main" only if the class is public. */
public class Fighter {

    // the Fighter class has three fields
    public int health;
    public int attack;
    public int speed;

    // the Fighter class has one constructor
    public Fighter(int health, int attack, int speed) {
        this.health = health;
        this.attack = attack;
        this.speed = speed;
    }
     // the Figher class has one method, so far...    
    public void roll(double block){
        block = (int)(Math.random() * 100);
    }
}

public class Attacker extends Fighter {

    // the Attacker subclass adds one field
    public int damage;

    // the Attacker subclass has one constructor
    public Attacker(int damage,
                        int health,
                        int attack,
                        int speed) {
        super(health, attack, speed);
        this.damage = damage;
    }   

    // the Attacker subclass adds one method
    public void attacked(int baseDamage){
        // Is human another class , then Fighter or did you mean Figher ? 
        if (super.roll()==block){
             return "Nothing happens";
        }
        else{
          int a = super.roll();
          human.health()-= damage;
        }
        if (super.health > 0){
           System.out.println(health);
        }  
    }
}
}

您也可以通过使用关键字 super 来调用覆盖的方法。

super.roll();

这个比较好帮忙?

你可以做的是在 subclass 中使用 extend 关键字,并使 void 方法 attacked 成为单独的 class ].现在他们将共享完全相同的方法,而且你们仍然可以 return 互相交流。

解决这个问题的另一种方法是再次将这两种方法分成两个单独的 classes,并将 subclass 嵌套在 superclass 的正上方最后一个括号。如果这是较大代码的一部分,您可以将多个序列嵌套在一起,或者只是将多个方法放在一起。不过你不需要将它添加到构造函数中,以上两个原因只是你可以尝试的事情,它们会给你相同的答案。

因为您正在 return 构建某些东西,所以您不需要将该方法添加到构造函数中!