Home > Software design >  If condition not working as expected in java class
If condition not working as expected in java class

Time:11-04

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 ; 
}

CodePudding user response:

Remove state variable from Television and Lamp classes.

Your base class Switchable has declared state variable already, and You should be using it. Both of Your classes Television and Lamp have their own declarations, shadowing the original one.

If You have a IDE (InteliJ) it should mentioned that you classes have variable of same name and type as the parent and mark is as warning.

So:

public abstract class Switchable {
    public State state = State.off; // set up to off by default
    abstract public void turn_on(); 
    abstract public void turn_off(); 
}

public class Television extends Switchable {
    
    public Television(){}
 ...
}

public class Lamp extends Switchable {
    
    public Lamp(){}
    ...
}
  • Related