Gither
Gither

Reputation: 1

Trying to use a variable from another class

public class Boss{

public void Attack1(){
    int randomspace = (int )(Math.random() * 3 + 1);
    System.out.println("Attacking space " + randomspace);
    if(space == randomspace){
        //Something right here to kill the player
    }
  }
}

But space is in a different class called Player

public class Player {
    int space = 1;
}

I thought about making a separate space variable and change them at the same time, but how would the Boss class know when to increment/decrement at the same time as the Player class. it would be easier to just keep it in the one class for simplicity.

EDIT: I figured it out. public class Boss extends Player{ and that fixed my problem

Upvotes: 0

Views: 47

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191681

Use parameters. (and lowercase your methods)

A boss will attack a space.

public void attack(int space){
    if(space == randomspace){
        //Something right here to kill the player
    }

If you need the Player, then you should really be using some abstract class, say Unit, then use Hero to be the main piece.

Then you can have

public void attack(Unit unit){
    if(unit.getSpace() == randomspace){
        //Something right here to kill the player
    }

And ideally unit.getSpace() could also come from some Board class that holds all information about the Unit types

Then, your logic elsewhere says boss.attack(player) or boss.attack(player.getSpace())

Upvotes: 1

Related Questions