michael michael - 3 months ago 15
Java Question

How to run a parents method twice

I'm Making a game which uses a parent to run an attack class as shown below

public String attack(int damage, int extradamage, String type) {

int hitpossibility;

hitpossibility = (int) ((Math.random() * 100) + 1);
if (type.compareTo("Ranged") == 0) {
weaponnoise = "twang!";

}else{
weaponnoise = "swing!";
}

if (chancetohit >= hitpossibility) {
for (int x = 0; x < damage; x++) {
result = result + (int) ((Math.random() * 6) + 1);
}
result = result + extradamage;
return weaponnoise + " The " + name + " did " + +result + " damage";


}
return weaponnoise +"The " +name+" missed!";
}


I have multiple different weapons which i want to use and have succeded in this however i have a dagger which i would like to attack twice per turn instead of once like the others. This is the class which i use to set the daggers damage values:

public class Dagger extends Blade {

public Dagger() {
super();
damage = 1;
extradamage = -1;
chancetohit = 75;
}

public String attack(int damage, int extradamage, String type) {

return super.attack(damage, extradamage, type);
}


I then have a class that runs it and currently it does this:

for (int l = 0; l < 2; l++) {
System.out.println(pointy.attack(pointy.damage, pointy.extradamage, pointy.getType()));
monsterhealth = monsterhealth - pointy.result;
System.out.println(monsterhealth);
pointy.result = 0;
}


Instead of it printing the attack twice, i want it to attack twice on the same line. I was wondering what i can change in the dagger class which would allow me to do so.
Any help is of course appreciated thank you!

Answer

This answer is an explanation of @Arnav 's comments. Here Dagger is a sub-class of the main weapon class and you want to invoke super-class' attack twice when the attack method of Dagger is called.

For this you need to call super.attack twice from Dagger attack method:

public class Dagger extends Blade {

public Dagger() {
super();
damage = 1;
extradamage = -1;
chancetohit = 75;
}

public String attack(int damage, int extradamage, String type) {
   String result1 = super.attack(damage, extradamage, type);
   String result2 =super.attack(damage, extradamage, type);
   return // You can return result1 or result2 based on your requirement
}

Note: I deleted my earlier answer, because this approach is better than the other one.