0

I use @SuperBuilder() in 2 class, I want override method build() of class child builder but it appear error "Abstract method 'build()' cannot be accessed directly" in line super.build() in ClassChild

Version Lombok: 1.18.28
Version java: 17

ClassParent.java

@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class ClassParent {
    private String name;
}

ClassChild.java

@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class ClassChild extends ClassParent {
    private int age;

    public static ClassChildBuilder builder() {
        return new BuilderCustom();
    }

    public static class BuilderCustom extends ClassChildBuilder {

        public ClassChild build() {
            ClassChild classChild = super.build();
            return classChild;
        }

        @Override
        protected ClassChildBuilder self() {
            return this;
        }
    }
}

Main class

ClassChild classChild = ClassChild.builder().name("Tom").age(20).build();

How should I fix to override the build() method success?

Thanks for reading.

Hoang
  • 829
  • 11
  • 18
  • 1
    Does this answer your question? [Customize lombok super builder](https://stackoverflow.com/questions/61658719/customize-lombok-super-builder) – Jan Rieke Jun 21 '23 at 14:28

1 Answers1

0

You can try below solution :

=> The issue you're experiencing is caused by the fact that the build() method in the ClassChildBuilder class is abstract, and you're trying to access it directly using super.build() in the BuilderCustom class. This is not allowed, as abstract methods cannot be accessed directly.

To override the build() method successfully, you can follow these steps:

[1] Remove the @SuperBuilder annotation from the ClassChild class. This will prevent Lombok from generating the ClassChildBuilder class with the abstract build() method.

[2] Modify the ClassChild class to extend ClassParent without the use of @SuperBuilder

Example :

@NoArgsConstructor
@AllArgsConstructor
public class ClassChild extends ClassParent {
    private int age;

    public static Builder builder() {
        return new Builder();
    }

    public static class Builder extends ClassChildBuilder {

        public ClassChild build() {
            ClassChild classChild = super.build();
            return classChild;
        }

        @Override
        protected Builder self() {
            return this;
        }
    }
}

[3] Make sure to update the self() method in the BuilderCustom class to return the appropriate type Builder instead of ClassChildBuilder. Now you should be able to override the build() method successfully and use the updated ClassChild.builder() method in your main code without encountering the abstract method error.

Satyajit Bhatt
  • 211
  • 1
  • 7
  • if don't use @SuperBuilder I don't find the class ClassChildBuilder. what it will be and how to create it? – Hoang Jun 21 '23 at 00:39