Search code examples
javainheritancecomposition

How to reach main class from composed ones when using composition?


I am using a composition of classes. The main class contains 2 other classes. My question is how can I reach my main class from composed classes? What might be the ways?

For example. We have Machine class with 2 Devices in it. All 3 classes have a boolean state active or not. We can turn on devices. The task is: when both devices are turned on THEN machine state is active. What methods can be used to achieve such behaviour?

public class Machine {

    private boolean active;

    private Device1 device1;
    private Device2 device2;

    public Machine(Device1 device1, Device2 device2) {
        this.device1 = device1;
        this.device2 = device2;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    public Device1 getDevice1() {
        return device1;
    }

    public Device2 getDevice2() {
        return device2;
    }

}

public class Device1 {

    private boolean active;

    public void turnOn(){
        // should check the state of another device and change machine state if necessary
        this.active = true;
    }

}

public class Device2 {

    private boolean active;

    public void turnOn(){
        this.active = true;
        // should check the state of another device and change machine state if necessary
    }

}

public class App {
    public static void main(String[] args) {

        Device1 device1 = new Device1();
        Device2 device2 = new Device2();

        Machine machine = new Machine(device1, device2);

        machine.getDevice1().turnOn();
        machine.getDevice2().turnOn();

        boolean active = machine.isActive();  // should be true
        System.out.println(active);

    }
}

After both devices are turned on then a machine active state should be true. How to achieve this?


Solution

  • If I understand your question, the method inside machine should be like this.

    public boolean isActive() {
            this.active = device1.isActive() && device2.isActive()
            return this.active;
     }
    

    You have to check whether all the defined devices have been turned on or not. It should be clear that each device should have a state which describes whether is active or not after turning off off turning on.