Reputation: 6551
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.
Upvotes: 4
Views: 3874
Reputation: 17454
When you apply final
on different things in Java, it gives you an almost totally different meaning.
final on variables
: Values cannot be assigned to it.
final on methods
: Methods cannot be overridden by sub-classes
final on classes
: That class cannot be extended by another class.
Hope that gives you something clear.
Upvotes: 7
Reputation: 2316
According to Oracle
You can declare some or all of a class's methods final. You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses.
So it depends on what you mean by completeness. Practically however, it really depends on whether you want the getters
to be overridden.
Upvotes: 1
Reputation: 178303
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()
.
Upvotes: 12