Search code examples
javaclassmethodsencapsulation

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


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


Solution

  • In your House class, add this:

    public House() {
        turnon();
    }
    

    I figured out the OP wants to have the first one's lights not turn on, so you can make a constructor with an argument of boolean called "lightsOn" and if true, it will turn on the lights, and if false, will not.

    public house(boolean lightsOn) {
        if (lightsOn) {
            turnon();
        }
    }
    

    Alternatively, you can simply add another constructor with an argument and only call that constructor on the first instance of "House"

    public House() {
        turnon();
    }
    
    // Only for the first house
    public House(boolean lightsOff) {
        turnon = false;
    }