Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 912
jmb95 Avatar asked Dec 26 '22 05:12

jmb95


2 Answers

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.

like image 138
Sergey Kalinichenko Avatar answered Dec 28 '22 07:12

Sergey Kalinichenko


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.

like image 26
Gio Avatar answered Dec 28 '22 06:12

Gio