How to keep the same value of a field for multiple calls to a Class

Viewed 162

I'm running into a problem that I can't solve basically, I'm trying to build a code for a house and I wanna make multiple calls to the house without having to turn on the light every single time

My field value

private boolean turnon = false;

and then my method to turn on the the lights

public void turnon() {
   
    turnon = true;
}

Basically what I want to avoid is to not call the method every single time I wanna add a new House, basically once I turn it on it turns on for every instance of the class.

House x = new House();
x.turnon(); 

So let's say I create another class of House

House y = new House();

I want the lights to be turned on in y since I've already turned them on in x

I tried defining the method statically but it didn't work, any suggestions would be appreciated

4 Answers

In your House class, add this:

public House() {
    turnon();
}

Whenever you are creating a new house, you can initialize the value of field turnOn(notice the camelcase convention ) in the constructor.

    public House(boolean turnOn) {
// initializing other fields 
        this.turnOn = turnOn; 
    }

Then you can provide regular getter and setter to access the turnOn field. When creating other houses , you can simply use your no-arg constructor.

    public House() {
// initializing other fields 
       
    }

The fundamental reason for the confusion here is: 'House' and a light 'Switch' don't belong to the same class!

So I think you should model House and a Switch as different classes. And just make the house object 'aggregate' a set of 'Switches' and other objects in the house.

Eg:

class House {
  List<ElectricalFitting> devices;
}

class Switch extends ElectricalFitting {
...
}

You can extract a default state for the light as static field into a base class. Your House class extends this base class, inhertites the default state field and copies in it's constructer the default to the instance state. The two setters change both, the default and instance state.

If for example the default state is light off (false), every new instance of House has it's light turned off.

But if you turn the light on (true) in one house than the default change to true and every new instance has the light turned on.

Every existing instance of House acts independenly to all other houses on turning light on or off.

public abstract class HouseBase {
    
    protectet static boolean defaultSwitchState = false;
    
}


public class House extends HouseBase {
    
    private boolean turnOn = false;
    
    
    public House() {
        turnOn = defaultSwitchState;
    }
    
    
    public void turnOn() {
        super.defaultSwitchState = true;
        turnOn = true;
    }

    public void turnOff() {
        super.defaultSwitchState = false;
        turnOn = false;
    }

}
Related