Constructor More Visible Than Class

ID

java.constructor_visibility_matches_class

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

code-style, reliability

Description

Reports constructors whose access modifier is broader than their enclosing class.

Rationale

A public constructor on a package-private class (or a public constructor in a private nested class) is misleading. External code cannot instantiate the class regardless of the constructor’s visibility, so the broader access modifier sends a false signal about the API surface. Aligning the constructor visibility with the class visibility makes the design intent explicit.

// Bad -- public constructor in package-private class
class Internal {
    public Internal() { }
}

// Bad -- public constructor in private nested class
public class Outer {
    private static class Secret {
        public Secret() { }
    }
}

Remediation

Reduce the constructor visibility to match or be narrower than the enclosing class.

// Good
class Internal {
    Internal() { }
}

public class Outer {
    private static class Secret {
        private Secret() { }
    }
}