Reputation: 642
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?
Upvotes: 0
Views: 556
Reputation: 31901
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
.
Upvotes: 1
Reputation: 994
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 (e.g. accessorExample.getAttribute();
).
Upvotes: 2
Reputation: 18233
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
Upvotes: 2