Deniz Yılmaz Deniz Yılmaz - 3 years ago 183
Java Question

Change the field of all objects of the class

I have a class with the boolean field and I want field of only one object to be true at the same time.

I tried to set field of all objects with static method but i could not reach non-static field from static method.(i wasn't aware of logic behind static)

public class ToggleBox
{
private boolean selected;

public ToogleBox()
{
selected=false;
}

public setOnlyTrue()
{
setAllFalse();
selected=true;
}
private static setAllFalse()
{
this.selected=false;
}

}


Is there any trick to do this or should i iterate over all objects of class to change all the fields?

Answer Source

One trick I could think of is having a static member that holds the reference of the one instance that has a true property:

public class MyClass {
    private static MyClass trueObject = null;

    public void setProperty(boolean value) {
        if (value) {
            trueObject = this;
        } else {
            trueObject = null;
        }
    }

    public boolean getProperty() {
        return trueObject == this;
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download