Why does only the class with the static method have the error: “Add a private constructor to hide the implicit public one.”?
Creating an instance of HasStaticMethod
would be a programmer mistake since it can serve (almost) no useful purpose ... as well as a harmful one (see below).
Declaring a private constructor will cause that programmer mistake (i.e. mistakenly instantiating HasStaticMethod
) to be flagged as a compilation error.
This is a good thing.
Why doesn't the class NotStatic have an error, too?
Because you need an instance of NoStatic
in order for call NoStatic.myPrint
. So you need a non-private constructor to make the instance. A default constructor will do ... because that will be public.
NoStatic.myPrint(); // compilation error
new NoStatic().myPrint(); // OK
You don't need an instance in the HasStaticMethod
case. The correct way to use it is:
HasStaticMethod.myPrint(); // OK
You could write this:
new HasStaticMethod().myPrint(); // compiles ... but bad
... but it doesn't do what the reader (most likely) thinks it does. The instantiation of the class is pointless, and calling a static method via an instance reference is downright misleading. That is the reasoning behind the IDE hint: to stop the programmer (who is using your HasStaticMethod
class) from accidentally or deliberately writing that kind of nonsense.
I think you may be thinking about this from the wrong perspective1. The goal is to write Java code that 1) works and 2) can be read and maintained by someone else. To that end, it is good thing when the IDE / Sonar warns us we are doing something that is liable to lead to problems. (And indeed, this is why we use tools like Sonar.)
Now you are free to twiddle with the Sonar settings to turn off this warning if you don't like it. Or stop using Sonar altogether. (But check with your coworkers and manager first, because they might have some opinions on that course of action.)
But my advice is to just add the private
constructor and declare the utility class as final
... as Sonar suggests. It is (IMO) a good thing to do.
1 - This should not be about "freedom of expression" or "personal choice". This is not poetry ...