Why is it a good practice to mark a class with only private constructors as final? My guess is, it is to let other programmers know that it cannot be sub-classed.
Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class.
private is about accessibility like public or protected or no modifier. final is about modification during inheritance. private methods are not just accessible from the outside of the class. final methods can not be overridden by the child class.
No, a constructor can't be made final. A final method cannot be overridden by any subclasses. As mentioned previously, the final modifier prevents a method from being modified in a subclass. The main intention of making a method final would be that the content of the method should not be changed by any outsider.
A private constructor in Java is used in restricting object creation. It is a special instance constructor used in static member-only classes. If a constructor is declared as private, then its objects are only accessible from within the declared class. You cannot access its objects from outside the constructor class.
It is often considered (e.g. by Josh Bloch and the designers of C#) good practice to mark everything as final unless you have an explicit reason not to. Assuming you mean class, you're correct that a class with only private constructors can't be subclassed. Thus, the final could be considered redundant, but as you say it has value for documentation. As Marc suggests, it may also aid optimization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With