1

In my class three instance variables which are all final. However, when I try to do something like this.inputsRelated = inputsRelated in the setter method, I get an understandable error which says final field cannot be assigned. But what would the approach in setter methods/how should I handle the methods public void setInputsRelated(boolean inputsRelated) and public void setExpected(int expected) ? Thanks in advance!

public class ExceptionLogicParameters extends RuntimeException {

    public final boolean inputsRelated;
    public final int expected;
    public final int found;

    public ExceptionLogicParameters(boolean inputsRelated, int expected, int found)
    {
        this.inputsRelated = inputsRelated;
        this.expected = expected;
        this.found = found;
    }

    @Override
    public String toString()
    {
        return "Get the the hell out of here!";
    }

    public boolean getInputsRelated()
    {
        return this.inputsRelated;
    }

    public int getExpected()
    {
        return this.expected;
    }

    public int getFound()
    {
        return this.found;
    }

    public void setInputsRelated(boolean inputsRelated)
    {
        this.inputsRelated = inputsRelated;
    }

    public void setExpected(int expected)
    {
        this.expected = expected;
    }

}
Shohin
  • 548
  • 1
  • 3
  • 14

4 Answers4

3

If the fields are final they can only be initialized in the variable declaration or in the constructor. Setter methods make no sense for final fields.

You should analyse your code and decide if the fields should indeed be final and, if that is the case, discard the setter methods. If you really need to create the setters, you must remove the final modifier.

Anderson Vieira
  • 8,919
  • 2
  • 37
  • 48
0

You should not have setters for final instance variables because you cannot set them. Either make your variables non-final or remove the setters.

Samuel
  • 16,923
  • 6
  • 62
  • 75
0

you can only getter methods, there is no use of setter method if final. If want to provide setter there no use of making them final.

Saif
  • 6,804
  • 8
  • 40
  • 61
0

Once you make a variable or reference final you are not allowed to change that and compiler will verify this and raise compilation error if you try to re-initialized final variables in java.

In your case the mutator and accessor (set/get) methods are useless due to the prior final declaration of your variable.

Algo
  • 91
  • 1
  • 2
  • 9