I was wondering why the final modifier is not used with getters and setters?
Why do this:
private int x;
public void setX(int x)
{
if(x >= 1) throw new IllegalArgumentException("X must be lower than 1");
this.x = x;
}
Instead of this:
private int x;
public final void setX(int x)
{
if(x >= 1) throw new IllegalArgumentException("X must be lower than 1");
this.x = x;
}
It does not improve the encapsulation? I have been trying to clarify it with google but I had not luck.
Thanks by advance.
One reason that you may want to leave a setter non-final is to let subclasses make their own, stricter, argument checks:
public class Subclass extends Superclass {
public void setX(int x) {
if(x >= 0) throw new IllegalArgumentException("X must be negative");
super.setX(x);
}
}
Of course this breaks Liskov Substitution Principle, because a subclass strengthens a precondition in a subtype.
The purpose of a final method in Java, is that it cannot be overridden or hidden by subclasses. Hence if you need that functionality for your getters / setters, it's perfectly fine to make them final, else there is no purpose for doing so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With