Java:S1118 false positive on class in function

Language: Java
Rule: S1118 (Utility classes should not have public constructors)

False positive because: for classes defined inside methods there is no difference between ‘private’ and ‘public’ (that is just the way Java works). So overriding the default public constructor by a private one doesn’t change anything.

I am using SonarLint in IntelliJ, version 10.4.2.78113 connected to our SonarQube for rule selection.

Example code:

public class Foo {
    public void someMethod() {
        final class Local { // S1118: Add a private constructor
            //private Local() {} // this will fix the warning but won't change anything else
            static final int SOME_CONST = 1234;
        }
        new Local(); // not possible to prevent this in Java, even with a private constructor
    }
}

This false positive requires to either suppress the warning or add a useless empty private constructor each time a utility class is added inside a method.

Hi there, thanks for the report.

Indeed in such a case, the addition of a private constructor only pollutes the code and does not change the accessibility of the class itself.

I created a ticket to fix the behavior, you can track its progress here.

Have a nice day!