When we want to close a class to inheritance we are declaring class with final,
final class Myclass {}
but when we declare the constructor private it will be the same effect,
class Myclass {
private Myclass() {}
}
But is it really the same? Is there any difference for optimization of code or readability of code? And which classes has to close to inheritance,
- immutable class maybe
- every method and member variable declared static of class
But for second option java.util.Arrays
hasn't been declared with final
even if all methods of Arrays
are declared static
.
Not necessarily, consider this example using static classes:
This will print "I have a private constructor".
When a developer sees that a class is final, they understand that the intention of the author was that it should not be extended.
When a developer sees that a class has a private constructor, they understand that the class can't be instantiated. This is generally because it is either a static utility class or a singleton.
This is a good observation. My guess is that it probably should have been but can't be changed now for backward compatibility.