This site requires JavaScript, please enable it in your browser!
Greenfoot back
malcolm098
malcolm098 wrote ...

2022/6/3

accessing a private boolean from a seprate actor class

malcolm098 malcolm098

2022/6/3

#
im trying to access a private boolean called "isTrash" in a actor class i have called "FoundItem" i'm haveing problems trying to check if it is true because i dont know how to check it from a different actor class thevariable has to stay private any help would be appreciated thankyou
Roshan123 Roshan123

2022/6/3

#
It's not possible to access anything from another class if you declared it as private. May be this may help you
Spock47 Spock47

2022/6/3

#
The typical way to make it possible to check the value of a private attribute is to add a getter-method:
private boolean isTrash;

public boolen getIsTrash() {
    return isTrash;
}
Now, the getter-method is public, so it can be called from outside the class. And since the attribute is private, the value can only be changed within the class and therefore is safe from "corruption". If you have a reference to an object of class FoundItem, you can now check whether this item is trash:
final FoundItem item; // needs to be initialized.
if (item.getIsTrash()) {
    // do whatever should be done with trash.
}
Note: The convention for the name of the getter of an attribute is normally using "get" and then the attribute name, e.g. "getName" for attribute name. However, for the special case of boolean attributes there is no definite naming convention; some possibilities are getIsTrash, isTrash, even isIsTrash... so just take the one you find fits the best / is best readable for you.
You need to login to post a reply.