How to use Lombok @Builder in abstract java class?

The answer is – you cannot, but you can use @SuperBuilder annotation instead of @Builder.

@SuperBuilder was introduced as experimental feature in lombok v1.18.2.
@SuperBuilder’s toBuilder feature and limited support for customization was added with lombok v1.18.4.

Short introduction

The Lombok project is the java library which will allow you to forget about getters, setters, builders, constructors etc. This library will automatically generate them and plug into your IDE and build tool.

Example of SuperPoint and Point3D

Let’s create abstract SuperPoint class which has two variables: X and Y which allow us to describe point in 2D world.

package com.bigdataetl.lombok;

import lombok.Getter;
import lombok.experimental.SuperBuilder;

@SuperBuilder
@Getter
public abstract class SupperPoint {

    private int x;
    private int y;

}

In the next step we are going to create child class Point3D which extends SuperPoint class. Additionally we will create Z variable for the third dimension. Take a look at the toString() method. I used the variables from SuperPoint class to print the X and Y values.

package com.bigdataetl.lombok;

import lombok.experimental.SuperBuilder;

@SuperBuilder
public class Point3D extends SupperPoint {

    private int z;

    @Override
    public String toString() {
        return "Point3D{" +
                "x=" + getX() + "," +
                "y=" + getY() + "," +
                "z=" + z +
                '}';
    }
}

Create object of Point3D

In the last step we will create the instance of Point3D class using Builder.

package com.bigdataetl.lombok;

public class LombokSuperBuilderMain {

    public static void main(String[] args) {

        Point3D point3D = Point3D.builder().x(5).y(10).z(15).build();
        System.out.println(point3D.toString());

    }

}

As the output you will see:

Point3D{x=5,y=10,z=15}

If you enjoyed this post please add the comment below or share this post on your Facebook, Twitter, LinkedIn or another social media webpage.
Thanks in advanced!

0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments