jeudi 21 juillet 2016

using enum with pattern builder in java

im trying to learn how to use pattern builder. i could get it to work until i tried to use enum.

I tried to change the code couple of times and each time had different error. right now the error is Incompatible types.

Please can you help bringing this code to working state and if you have suggestions to improve the code it would be great.

thanks.

public class Person
{
private final String name;
private final String lastname;
private final int age;

//My enum im trying to use
private Status status;
private enum Status
{
    SINGLE ("Single"), MARRIED ("Married"), WIDOWER ("Widower");

    private String status;

    private Status(String status)
    {
        this.status = status;
    }

    public String getStatus()
    {
        return this.status;
    }
}

//builder
private Person(PersonBuilder builder) {
    this.name = builder.name;
    this.lastname = builder.lastname;
    this.age = builder.age;
    this.status = builder.status; // Error: Incompatible types
}

//GETTERS
public String getName() {
    return name;
}

public String getLastname() {
    return lastname;
}

public int getAge() {
    return age;
}

@Override
public String toString() {
    return "Person : "+this.name+", "+this.lastname+", "+this.age;
}

//PersonBuilder
public static class PersonBuilder
{
    private final String name;
    private final String lastname;
    private int age;
    private Status status;
    private enum Status
    {
        SINGLE ("Single"), MARRIED ("Married"), WIDOWER ("Widower");

        private String status;

        private Status(String status)
        {
            this.status = status;
        }

        public String getStatus()
        {
            return this.status;
        }
    }

    public PersonBuilder(String name, String lastname) {
        this.name = name;
        this.lastname = lastname;
    }

    public PersonBuilder age(int age) {
        this.age = age;
        return this;
    }

    public PersonBuilder status(Status status)
    {
        this.status = status;
        return this;
    }

    public Person build() {
        Person person =  new Person(this);
        return person;
    }

}

Aucun commentaire:

Enregistrer un commentaire