Search code examples
javaintellij-ideafinal

Are 'final' field modifiers superflous in an immutable class?


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?


Solution

  • 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.