0

I want to print true, in the main method, if the member variable is off. How do I do this without changing the types from void to boolean as off needs to remain void.

The code for the SmartDevice class is here

public class SmartDevice extends Device {

    private boolean member;


    public SmartDevice() {

    }


    @Override
    public void on() {

    }

    @Override
    public void off() {

    }
}

The code where I need the tweek,

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

       //smart device
        SmartDevice smartDevice = new SmartDevice();

        //up casting
        Device upCastedSmartDevice = new SmartDevice();

        //down casting
        Device device = new SmartDevice();
        SmartDevice downCastedSmartDevice = (SmartDevice) device;

        //call methods
        smartDevice.on();
        smartDevice.off();

        //passing devices into switch methods
        System.out.println();

        //smart device
        aSwitch.turnOn(smartDevice);
        aSwitch.turnOff(smartDevice);
        System.out.println();

        //down casted smart device
        aSwitch.turnOn(downCastedSmartDevice);
        aSwitch.turnOff(downCastedSmartDevice);
        System.out.println();

        //up casted smart device
        aSwitch.turnOn(upCastedSmartDevice);
        aSwitch.turnOff(upCastedSmartDevice);
        System.out.println();
Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
  • What is the purpose of the boolean variable 'member' in SmartDevice class?, if it represents the on/off status of the Device, you can write two methods called isOn(), isOff(), returning the member variable's value. And in the main function, you can simply print by calling isOn() or isOff() methods – ram914 Oct 17 '19 at 11:09

1 Answers1

0

There are multiple possibilities to achieve a solution for that problem. 1. Add a Method e.g. isOn in your SmartDevice class (recommended)

public boolean isOn() {
  return member;
}
  1. If you really don't want to modify your SmartDevice class, you could use Reflection. But this does indeed break the contract of your OOP design so I would strongly dissuade doing that.

  2. Print true in your SmartDevice after method off() is being called.

Joel
  • 138
  • 10