Home > OS >  How do you have a class change the value of an attribute of another class?
How do you have a class change the value of an attribute of another class?

Time:10-10

Let's say I have a class which is a door with an attribute that states whether it's open or closed. Then there is another class which is a person that is assigned to that door. How would you tell the person to open/close the door? (change the value of the attribute in the door class with a method in the person class)

CodePudding user response:

You mean something like this?

class Door {
    public boolean closed = true;
}

class Person {

    Door door = new Door();
    
    public void changeDoorState(boolean closed) {
        door.closed = closed;
    }

}

CodePudding user response:

If you want to set the door state, you can pass a value in a setter as follows. I would use an enum for this since it is more descriptive.

enum Door {
    CLOSED, OPEN
}
Door door = Door.OPEN;

System.out.println(door);
changeDoorState();
System.out.println(door);
setDoorState(door.OPEN);
System.out.println(door);

public void setDoorState(Door status) {
    door = status;
}

public boolean isDoorOpen() {
    return door == Door.OPEN;
}

If you want to change the door state then do something like this.

public void changeDoorState() {
    // ternary - if door is open set to closed, else set to open
    door = door == Door.OPEN ? Door.CLOSED : Door.OPEN;
}
  • Related