Search code examples
javafinalgetter

Java Final Getters


Given the following class:

public class SomeClass {

    private final int a;

    public SomeClass(int a) {
        this.a = a;
    }

}

Which is more appropriate in terms of completeness?

public final int getA() {
    return a;
}

OR

public int getA() {
    return a;
}

In my opinion, both are equivalent, so I wouldn't even bother putting final.

But for the sake of being complete, the first method seems more "correct" than the second.


Solution

  • The keyword final means something completely different when applied to a method as opposed to applied to a variable.

    On a method, it means that no subclass can override the method. It has nothing to do with not changing a value. So, your two choices are not equivalent, because of whether a subclass may override getA().