How to deal with Inheritance while using Lombok builder

Reading Time: 2 minutes

Today, I came across a problem and found a beautiful solution for it, which is pretty much straight forward, but the problem may occur to anyone while using the Lombok Library for java. So let’s look at the problem.

The Problem

I have a class Person, which consists of some fields. It is annotated with the @Builder annotation of lombok, so that lombok can generate the builder for this class. Below is the code for the class Person –

Now, I created a sub-class of Person, Student, since it needs all the fields from Person plus an additional field. I again used @Builder annotation on it to generate the builders for this class as well. Below is the code for Student –

Now, what I expected was that every thing will run smoothly and I will be able to access the fields of parent class from child class builder and live my life happily. But NOPE!! Accessing parent class fields from child class builder is not allowed. So, the problem was to build a class, that is inheriting fields from a super class also having the @Builder annotation. So, let’s see how I was able to solve it.

The Solution

The solution was amazingly simple. First, you will have to define a constructor for the Student class, passing all the fields you want in Student, i.e., fields of Person as well as Student. You will now notice that the Person fields are now accessible from Student builder. But now, when you try to compile the program, it will throw an exception stating that the return type of child builder is incompatible with the parent builder. This happens because the child class is trying to expose both, its own and parent class’ builder, with same name. If we change the name of the builder of any one class, then we will be able to solve this problem. To give a custom name to the builder, we can use the builder argument builderMethodName and assign it to a builder name. The new code for Student class is as below –

Now, instead of using Student.builder() we will use Student.studentBuilder(), and now when we compile our program, we will be able to compile it successfully and can now use our Student object freely.

I hope this blog was helpful for you and you got to learn something new. Thanks and happy blogging!

Written by 

Akshansh Jain is a Software Consultant having more than 1 year of experience. He is familiar with Java but also has knowledge of various other programming languages such as scala, HTML and C++. He is also familiar with different Web Technologies and Android programming. He is a passionate programmer and always eager to learn new technologies & apply them in respective projects.