So i was making a dependecy inversion principle example and i'm getting the wrong output from the class powerSwitch which is supposed to turn the lamp or the televesion (which extend the switchable abstract class) on if it's off and off it's currently on using the functions turn_on/turn_off and print its current state (on/off).
I tried to call the clickSwitch() twice to get diffrent results but but all i'm getting as output is "lamp's off"
public abstract class Switchable {
public State state;
abstract public void turn_on();
abstract public void turn_off();
}
public class Lamp extends Switchable {
public State state;
public Lamp()
{
state=State.off;
}
public void turn_on()
{
this.state=State.on;
System.out.println("lamp's on");
}
public void turn_off()
{
this.state=State.off;
System.out.println("lamp's off");
}
}
public class Television extends Switchable {
public State state;
public Television()
{
state=State.off;
}
public void turn_on()
{
this.state=State.on;
System.out.println("lamp's on");
}
public void turn_off()
{
this.state=State.off;
System.out.println("lamp's off");
}
}
public class PowerSwitch {
Switchable sw;
public PowerSwitch(Switchable sw)
{
this.sw=sw;
}
public void ClickSwitch()
{
if(sw.state==State.off)
{
sw.turn_on();
}
else
{
sw.turn_off();
}
}
}
public class Main {
public static void main(String[] args) {
Switchable sw=new Lamp();
PowerSwitch ps=new PowerSwitch(sw);
ps.ClickSwitch();
ps.ClickSwitch();
}
}
public enum State {
on , off ;
}