Self Recursive Generics in Java and Builder Pattern

Sometimes instantiate a class might be harder with constructor than using builder pattern. Like StringBuilder we might want to construct our object with simple methods. And this is called Buildder pattern .

Also we would like to have an ability to like we have in StringBuilder which is called fluent builder methods. We can call method from string builder such as append and then we are able to call another append method .

StringBuilder sb = new StringBuilder();
sb.append("First line").append("Second line")

So to achieve this ability we need to use self recursive generic in our builder factory class.

Here is you how to implement a PersonBuilder Factory class and EmployeeBuilder class with self generics.

package com.company;


class Person {
    public String name;
    public String position;

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", position='" + position + '\'' +
                '}';
    }

}

class PersonBuilder<SELF extends PersonBuilder<SELF>> {
    protected Person person = new Person();


    public SELF withName(String name) {
        person.name = name;
        return self();
    }
    public  Person build() {
        return person;
    }

    protected SELF self() {
        return (SELF) this;
    }


}

class EmployeeBuilder extends PersonBuilder<EmployeeBuilder>
{
    public EmployeeBuilder worksAt(String position) {
        person.position = position;
        return self();
    }

    protected EmployeeBuilder self() {
        return this;
    }


}

public class Main {
    public static void main(String[] args) {
        EmployeeBuilder pb = new EmployeeBuilder();
        Person ozan = pb
                .withName("Ozan")
                .worksAt("Argela")
                .build();
        System.out.println(ozan);
    }


}

Leave a Reply

Your email address will not be published. Required fields are marked *