JQBolo JQBolo - 1 month ago 4
Java Question

Possible to utilize setter cross-class in java

I'm trying to access an objects setter from another class for a minesweeper game, and am unsure if it is actually possible.

Essentially I have a Board class which contains all the logic for setting up the board, and inside my main method I want to prompt the user to enter an int, which then communicates this value to

Board.setHealth()
.

My prompt in my main method (contained in
Mines.java
) is as follows

if (keyboard.nextInt() < 1) {
throw new Exception("Number must be higher than 0!");
}
else health = keyboard.nextInt();
Board.setHealth(health);


in my
Board.java
constructor I am declaring 2 ints,
startHealth(1)
and
health(not yet defined)


My board setHealth method is as follows

public void setHealth(int health){
this.health = health;
}


Now, the error I'm getting currently is

non-static method setHealth(int) cannot be referenced from a static context
.

My understanding is that I'm attempting to setHealth on an object which is not yet instantiated (which was an error I had during a different phase where I wasn't utilising a setter method), so how do I redesign my method to allow this?

Answer

No... you are trying to call setHealth by using static way but you didn't declare it as static You can use your code only if you declare your method in this way

  public static void setHealth(int health){
    this.health = health;
  }

But if you do it in this way, also healt should be static and static variables are common to all the instances of a class so it's not a good strategy

In your case in your main method you should do something like this

if (keyboard.nextInt() < 1) {
  throw new Exception("Number must be higher than 0!");
}
else health = keyboard.nextInt();
Board b = new Board();
b.setHealth(health);

I hope this can help

Comments