Skip to content

[java] AccessorClassGeneration false-negative: subclass calls private constructor #1998

@Vampire

Description

@Vampire

Rule: AccessorClassGeneration

Possibly a false-negative.

Having a sub-class that calls a private constructor is bad practice.
It requires the compiler adding another package-private synthetic constructor with an additional synthetic anonymous inner class parameter that forwards to the private constructor so that the subclass has something non-private to call.

Examples for this would be for example

class Foo {
    private Foo() { }
    public Foo(String foo) { }
    private static class Bar extends Foo { }
}

where the default constructor of Bar calls the private no-arg constructor of Foo or

class Foo {
    private Foo() { }
    private Foo(String foo) { }
    public Foo(String foo, String bar) { }
    private static class Bar extends Foo {
        public Bar() { super(null); }
    }
}

where the call to the private constructor is explicit.

This adds unnecessarily additional constructors and also can cause problems if you use the class from Groovy code, as in the first example new Foo(null) and in the second example new Foo(null, null) can not be executed as there is a disambiguity between the constructor you meant to call and the synthetic added constructor.

It is usually better practice to simply make that constructor package-private direclty, eliminating the need for any synthetic constructors.

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-negativePMD doesn't flag a problematic piece of code

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions