By making private constructor, we can avoid instantiating class from anywhere outside. and by making class final, no other class can extend it. Why is it necessary for Util clas
It's not necessary, but it is convenient. A utility class is just a namespace holder of related functions and is not meant to be instantiated or subclassed. So preventing instantiation and extension sends a correct message to the user of the class.
There is an important distinction between the Java Language, and the Java Runtime.
When the java class is compiled to bytecode, there is no concept of access restriction, public
, package
, protected
, private
are equivalent. It is always possible via reflection or bytecode manipulation to invoke the private
constructor, so the jvm cannot rely on that ability.
final
on the other hand, is something that persists through to the bytecode, and the guarantees it provides can be used by javac to generate more efficient bytecode, and by the jvm to generate more efficient machine instructions.
Most of the optimisations this enabled are no longer relevant, as the jvm now applies the same optimisations to all classes that are monomorphic at runtime—and these were always the most important.
By default this kind of class normally is used to aggregate functions who do different this, in that case we didn't need to create a new object
This is not a mandate from functional point of view or java complication or runtime. However, its coding standard accepted by wider community. Even lot of static code review tools like checkstyle and many others checks that such classes have this covention followed.
Why this convention is followed , is already explained in other answers and even OP covered that.
I like to explain it little further , mostly Utility classes have the methods/functions which are independent of object instance. Those are kind of aggregate functions.As they depend only on parameters for return values and not associated with class variables of utility class. So, mostly these functions/methods are kept static. As a result, Utility classes are ideally classes with all the static methods. So, any programmer calling these methods don't need to instantiate this class. However, some robo-coders (may be with less experience or interest) will tend to create object as they believe they need to before calling its method. To avoid that creating object, we have 3 options :-
Now, again if someone wants to add new method for some functionality to these utility class , he don't need to extend it , he can add new method as each method is indepenent and no chance of breaking other functionalities. So, no need to override it. And also you are not going to instiantiate, so need to subclass it. Better to mark it final.
In summary , Creating object of utility classes does not make sense. Hence the constructors should either be private. And you never want to override it ,so mark it final.