0

I typically have such small class definition, as below:

public static class Annotation {
    private final String brand;
    private final Sentiment sentiment;

    public Annotation(String brand, Sentiment sentiment) {
        this.brand = brand;
        this.sentiment = sentiment;
    }

    public String brand() {
        return this.brand;
    }

    public Sentiment sentiment() {
        return this.sentiment;
    }
}

There is no any method that can modify 'brand' and 'sentiment' by a client. If I remove the 'final' modifier, my IntelliJ gives me a warning, saying that I should add the 'final' method.

Is it good practice to always add 'final' in such cases?

howlger
  • 31,050
  • 11
  • 59
  • 99
marlon
  • 6,029
  • 8
  • 42
  • 76
  • 2
    Writing code is not just about performing a task. You are describing the task to your colleagues and your future self. By marking these members as final you are communicating to anyone who edits this class that the intention is that these members a should not be changed. – bhspencer Oct 05 '17 at 18:31
  • This is not a duplicate of the cited question. This question is asking about making the private member variables `final`, while the cited question is about making the _Class_ itself final, so it can't be extended. – Stephen P Oct 05 '17 at 18:45
  • Making it final is a matter of opinion anyway. It will be all right either way. – Meo Oct 05 '17 at 21:59

1 Answers1

1

IntelliJ suggests the variable to be final as far as possible because it will prevent you from accidental modification of the variable.

Also sometimes Java compiler optimizes the code if static final modifier is used.

Nabin Bhandari
  • 15,949
  • 6
  • 45
  • 59