Do I need each method in a class to be in the constructor for the subclasses to inherit?

advertisements

So, I have this class that I made, called fighter. I made it work for a minute. Then, I added this method:

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

This may sound stupid, but do I need to add it to the constructor to inherit the class? I want to do this with a 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);
  }

}

So then, do I add roll() to the constructor or is there another way of doing it?


Well to answer the question

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

The answer is no. Just call what you want in the constructor. If you want to use a certain method from the subclass, then just make an instance of that class and call the method

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

Is this what your asking ?

subclass inherits all the fields and methods of Super class and you can add the fields/variables and methods to set it. Except for the constructor.

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

You could also invoke the overridden method through the use of the keyword super.

super.roll();

This better help out ?