Java – should the mandatory utility class be final and private constructors?

By creating private constructors, we can avoid instantiating classes from anywhere outside By making the class final, no other class can extend it Why do util classes need private constructors and final classes?

Solution

From a functional point of view, this is not a task, nor is it a Java complex or runtime However, its coding standard is accepted by the wider community Even many static code review tools (such as checkstyle and many others) check whether these classes comply with such regulations

The reason for following this practice has been explained in other answers, and even OP covers this

I want to further explain that most utility classes have methods / functions that are independent of object instances These are aggregate functions Because they depend only on the parameters of the return value and not on the class variables of the utility class Therefore, most of these functions / methods are static Therefore, the utility class is ideally a class with all static methods Therefore, any programmer who calls these methods does not need to instantiate this class However, some robot coders (who may not have experience or interest) will tend to create objects they think they need before calling their methods To avoid creating objects, we have three options: –

>Continue to educate people not to instantiate it (people without reason can continue to do so.) > Mark the class Abstract: – now Robo coders won't create objects again However, reviews and the wider Java community will argue that tag abstraction means you want someone to extend it Therefore, this is not a good choice. > Private Builder: - protected will again allow subclasses to create objects

Now, again, if someone wants to add new methods for these utility classes, he doesn't need to extend it. He can add new methods, because each method is independent and has no chance to destroy other functions Therefore, there is no need to overwrite it And you won't see it, so you need to subclass it It is best to mark it as final

In short, creating objects for utility classes makes no sense Therefore, constructors should be private And you never want to overwrite it, so mark it at last

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>