Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

final double in constructor java

I have trouble understanding why double xx and yy are put final in the constructor. Why don't I just put them double xx and double yy. Why do they have to be final? I guess the whole purpose of this is creating an immutable object.

public class Point {
private final double x, y;
private double distance; 

 public Point(final double xx, final double yy) {
  this.x = xx;
  this.y = yy;
  this.distance = -1; 
 }

}
like image 641
Timo N. Avatar asked Aug 10 '26 20:08

Timo N.


1 Answers

There is no need for these parameters to be final.

There are two reasons to make parameters final:

  1. To make use of them in an inner class declared in that function;
  2. To prevent their values from being changed accidentally.

Clearly (1) doesn't apply.

(2) isn't necessary because it's such simple code, and you can see that it's not changing the parameters.

There is a school of thought which says that all parameters and local variables should be declared final as a matter of course, as it makes it easier to reason about the code, in the same way that using immutable types makes it easier to reason about code using them.

There is another school of thought which says that adding final everywhere is just unnecessary noise, and, if you are writing methods where you can't tell if the value is changing, your methods are too long.

Largely, making parameters and local variables final comes down to personal/team preference.

like image 93
Andy Turner Avatar answered Aug 13 '26 10:08

Andy Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!