Austin Yang
Austin Yang

Reputation: 13

Error while use builder(lombok) in constructor annotation

@Data
@Builder
public static class Common {
    private String common1;
    private String common2;
}

@Getter
public static class Special extends Common {
    private String special1;

    @Builder
    public Special(String common1, String common2, String special1) {
        super(common1, common2);
        this.special1 = special1;
    }
}

The below error occurs :

Error:(149, 9) java: builder() in com.example.home.ExampleDTO.Special cannot override builder() in com.example.home.ExampleDTO.Common   
return type com.example.home.ExampleDTO.Special.SpecialBuilder is not compatible with com.example.home.ExampleDTO.Common.CommonBuilder

And when I put (builderMethodName = "b") this parameter in @Builder(Special constructor) then it works fine.

@Builder(builderMethodName = "b")
public Special(String common1, String common2, String special1) {

I have no idea, why the first code gives error. Please help me out. Thank you

Upvotes: 1

Views: 810

Answers (1)

Jan Rieke
Jan Rieke

Reputation: 8142

@Builder creates a static method builder() in both classes; it returns an instance of the respective builder. But the return types of the methods are not compatible, because SpecialBuilder and CommonBuilder are different and unrelated classes: @Builder does not (and can not technically) consider the inheritance relation between the classes. So the compiler complains about two methods with the same name, no arguments, but different return types. This is not possible in Java.

To solve this you have two choices:

  1. Use @SuperBuilder on both classes. @SuperBuilder is designed to work with inheritance.

  2. As you already found out, you can rename the method in one of the classes.

Upvotes: 4

Related Questions