Search code examples
javamethodstypesargumentsrequired

How to set required constants for methods?


I am creating a method called setState and I want to use binary operators for it, but I want to create something to check if the passed argument is a constant defined in the class:

public static final int STATE1 = 0b1;
public static final int STATE2 = 0b10;
public static final int STATE3 = 0b100;
public void setState(int stateType, boolean state){
    if(state){
        this.state |= stateType;
    }else{
        this.state &= ~stateType;
    }
 }

So when I type setState(10, false) it will say: Wrong argument type, found x, required y


Solution

  • you only want stateType to be one of STATE1, STATE2, or STATE3? You could use an enum defined in that class. Something like:

    public class MyClass{
        public enum State{
            STATE1 (0b1),
            STATE2(0b10),
            STATE3(0b100);
    
          public final int value;
          State(int value){
            this.value = value;
          }
        }
    
       public void setState(State stateType, boolean state){
        if(state){
            this.state |= stateType.value;
        }else{
            this.state &= ~stateType.value;
        }
      }
    }