Time after time I have a situation where I have an utility class containing only static methods.
The question is not about the fact of having such classes themselfes, so not a debate about utility classes. We just assume that there is a use case where this class makes sense.
Now I have seen different possibilities to prevent instantiation/extension:
What is the best practice here? Could you elaborate the benefits/drawbacks of the two possibilities?
Personally I prefer the enum solution, as it completely prevents instantiation and extension out of the box, but maybe I am wrong.
Thank you already!
I would prefer the former.
First of all, using a final class with a private constructor is what I do all the time when I'm writing a utility class. I have never even thought of using enums.
The main reason for not using an enum is that you can still technically write something like this:
MyEnum var = MyEnum.valueOf("Hello");
and the compiler doesn't say a thing about it, not even IntelliJ IDEA!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.