Search code examples
javaoopencapsulationaccess-modifiers

Is it a good idea to use 'final' modifier with getters and setters?


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.


Solution

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