javaabstract-classlombokbuilder

Spring Boot Builder with abstract classes


I have a class called Property which is an abstract class and has the following properties:

@SuperBuilder
@Setter
@Getter
public abstract class Property {

    private String id;

    private String address; //TODO -> Create Value Object

    private String description;

    private Float squareFootage;

    private Integer bedrooms;

    private Year yearBuilt;

    private Integer bathrooms;

    private Heating heatingType;
}

I have two more classes called Apartment and House which extend this property class

@EqualsAndHashCode(callSuper = true)
@Builder
@Getter
@Setter
@Data
public class Apartment extends Property {

    private Long houseId;

    private Integer floor;

}

I got the error error: no suitable constructor found for Property(no arguments) @Builder error: no suitable constructor found for Property(no arguments)

I do understand that you cannot instantiate abstract classes, I provided a constructor to the abstract class so the child classes can use it as super() and I got the following error error: no suitable constructor found for Property(no arguments) @Builder ^ constructor Property.Property(String,String,String,Float,Integer,Year,Integer,Heating,EnergySource,FlooringType,List,List,double,double) is not applicable (actual and formal argument lists differ in length) constructor Property.Property(PropertyBuilder) is not applicable (actual and formal argument lists differ in lengt


Solution

  • You need to annotate Apartment with @SuperBuilder as well, not with @Builder.

    The @SuperBuilder annotation produces complex builder APIs for your classes. In contrast to @Builder, @SuperBuilder also works with fields from superclasses. However, it only works for types. Most importantly, it requires that all superclasses also have the @SuperBuilder annotation.

    Also, there is no need to explicitly add @Getter and @Setter when you are using @Data.

    @Data is a convenient shortcut annotation that bundles the features of @ToString, @EqualsAndHashCode, @Getter / @Setter and @RequiredArgsConstructor together