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

时间:2015-08-19 01:45:05

标签: java inheritance parameters arguments

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

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

这可能听起来很愚蠢,但是我需要将它添加到构造函数来继承该类吗?我想用子类

来做这件事
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()添加到构造函数中,还是有另一种方法呢?

2 个答案:

答案 0 :(得分:1)

您可以使用子类中的extend关键字,并将void方法attacked放入单独的类中。现在他们都会分享完全相同的方法,你仍然可以互相回报。

另一种解决此问题的方法是再次将这两个方法分成两个独立的类,并将子类嵌套在最后一个括号上方的超类下面。如果这是更大代码的一部分,您可以将多个序列嵌套在一起,或者只将多个方法放在一起。您不需要将它添加到构造函数中,上述两个原因只是您可以尝试的内容,它们会给您相同的答案。

因为你要返回的东西你不需要将这个方法添加到构造函数中!

答案 1 :(得分:-1)

很好地回答这个问题

  

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

答案是否定的。只需在构造函数中调用您想要的内容即可。如果要使用子类中的某个方法,则只需创建该类的实例并调用方法

Object object = new Object("your constructor info"); 
object.newMethod. 
这是你的要求吗?

子类继承了Super类的所有字段和方法,您可以添加字段/变量和方法来设置它。除了构造函数。

 /* 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();

这样更好帮忙吗?