简体   繁体   中英

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?

The private modifier implies that you don't have access to the property directly. But perhaps more importantly, private implies that you shouldn't have access to the property directly. Create a getter for providing access to external classes:

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

    public String getTargetNumber() {
        return targetNumber;
    }

    //rest of the code
}

class GiveUpButton implements ActionListener {
    public void actionPerformed(ActionEvent gEvent) {
        GameUtility utility = new GameUtility();
        textArea.append(utility.getTargetNumber());
    }
}

See also: Java Documentation on Access Control

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 (accessor) 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 AccessorExample {
    private String attribute;

    public String getAttribute() {
        return attribute;
    }

    public void setAttribute(String attribute) {
        this.attribute = attribute;
    }
}

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 (eg accessorExample.getAttribute(); ).

The recommended way is to create appropriate Getters and Setters .

See this post to get more insights as how do getters and setters work?

public class AccessorExample {
    private String attribute;

    public String getAttribute() {
        return attribute;
    }

    public void setAttribute(String attribute) {
        this.attribute = attribute;
    }
}

Most of the IDEs provide support to directly generate getters and setters .

  1. Generate Getters and setters in Netbeans.
  2. Generate Getters and setters in Eclipse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM