mercredi 19 janvier 2022

How to write Builder Pattern for class that extends abstract class in Java?

I have the "Client" class that extends abstract class "User":

public abstract class User {
    private Long id;
    private String firstName;
    private String lastName;
    private String email;

   //getters and setters
}

public class Client extends User{
    private List<Account> accountList;

    //getters and setters
}

I have written the builder for the "Client" class, but I can't have access to the User's fields (id, firstName, lastName, email) for use it all in building. How to do it?

public class Client extends User {
    private List<Account> accountList;

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


    public class Builder {
        private Builder() {
        }

        public Builder setAccountList(List<Account> accountList) {
            Client.this.accountList = accountList;
            return this;
        }

        public Client build() {
            return Client.this;
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire