Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it compulsion to make field as final to make class immutable

I have doubt a doubt regarding making an immutable class.

As per the java docs.

  1. I made the class final( no one can extend)
  2. field are private.
  3. no setter function.
  4. If fields are mutable then send a cloned copy of the field.

My doubt is that its compulsory to make a field of my class as final?

like image 644
dead programmer Avatar asked Dec 12 '25 01:12

dead programmer


1 Answers

If there are no setter methods (and presumably no other methods to affect the fields' values) and the fields themselves are private, marking them as final is somewhat redundant. Having said that - its a good defensive practice which many projects' standards follow.

like image 155
Mureinik Avatar answered Dec 13 '25 16:12

Mureinik



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!