0

I am a beginner in JAVA and came across this doubt in Singleton class:

Since while creating an immutable class in JAVA we make its properties as private, why is there a need to make them final then? We don't have setters in immutable and also the properties are private so that they can't be accessed from outside to change them.

So why make them final then?

ghostrider
  • 2,046
  • 3
  • 23
  • 46
  • 5
    In short, making them `final` means that if we change something inside the class and accidentally try to change it, the compiler will flag it. It may seem pointless if your class is 10 lines long, but try keeping track of a 300-line class without `final`. – Silvio Mayolo Jul 07 '18 at 03:21
  • 2
    And software is not just composed of a single class, but can be millions of lines of code. Having the machine enforce some rules (like `final`) that a human doesn't have to track is very valuable. – markspace Jul 07 '18 at 03:23

1 Answers1

1

Related: Do java finals help the compiler create more efficient bytecode?

Also related: Does use of final keyword in Java improve the performance?

The answer to the above questions is "theoretically yes, but in practice probably not" by the way. In this case, I don't think that it would make much of a performance difference (and even if it did, it would probably be a microoptimization at best).

With that said, the main advantage (and this is alluded to in the linked questions as well) is to document and enforce the design intent. Marking something as final could actually tell you a lot about how a particular item fits into the overall design, and about how you intend to use it later.

It also serves as an enforcement mechanism.

This helps prevent people from accidentally "blowing away" a design decision because they didn't know about it, especially if your class changes, becomes more complicated, etc.

TL;DR While it's not required, it helps to emphasize the fact that it's designed to be immutable.