TaeHyun. A TaeHyun. A - 1 month ago 11
Java Question

How to access a value of a private instance variable from a different class?

I am creating a simple GUI game (number guessing) in Java.

Apparently, I have a button called

Give Up
.

When I click the
Give Up
button, I want to display the answer on a textarea.

However, the
targetNumber
variable is declared as private:

public class GameUtility {
private String targetNumber = "2543";

//rest of the code
}

class GiveUpButton implements ActionListener { //Inner class
public void actionPerformed(ActionEvent gEvent) {

GameUtility utility = new GameUtility();
textArea.append(utility.targetNumber); //How to access the value of targetNumber?
}
}


How can I access a value of a private variable?

Answer

To make the state of the managed bean accessible, you need to add setter and getter methods for that state.

Once the setter and getter methods have been added, you can update and access the value of the private instance. The code should look like the following example:

public class Printer {
    private String salutation;

    public void setSalutation(String salutation) {
        this.salutation = salutation
    }

    public String getSalutation() {
        return salutation;
    }
}

Letting access the information inside the private instance from outside of the class, only if they ask through a provided mechanism we will call method. The mechanisms for asking an object to reveal information about itself we can call the getter method (e.g. printer.getSalutation();).