Что не так с моим шаблоном строителя?

У меня проблема с реализацией шаблона Builder. У меня есть 2 класса:

package course_2;

import java.util.Date;

public class Student {
    private static int idStart = 0;

    private final int id = idStart++;
    private String name;
    private String surname;
    private String secondName;
    private Date birthDate;
    private String address;
    private String phone;
    private int course;
    private int group;

    public static class Builder {
        // Обязательные параметры
        private final String name;
        private final String surname;
        private final Date birthDate;
        // Необязательные параметры, инициализация по умолчанию
        private String secondName = "";
        private String address = "";
        private String phone = "";
        private int course = 1;
        private int group = 1;

        public Builder(String name, String surname, Date birthDate) {
            this.name = name;
            this.surname = surname;
            this.birthDate = (Date) birthDate.clone();
        }

        public Builder SecondName(String secondName) {
            this.secondName = secondName;
            return this;
        }

        public Builder address(String address) {
            this.address = address;
            return this;
        }

        public Builder phone(String phone) {
            this.phone = phone;
            return this;
        }

        public Builder course(int course) {
            this.course = course;
            return this;
        }

        public Builder group(int group) {
            this.group = group;
            return this;
        }
    }

    private Student(Builder builder) {
        this.name = builder.name;
        this.surname = builder.surname;
        this.secondName = builder.secondName;
        this.birthDate = builder.birthDate;
        this.address = builder.address;
        this.phone = builder.phone;
        this.course = builder.course;
        this.group = builder.group;
    }
}

Проблема в том, что когда я пытаюсь вызвать Builder из своего клиентского кода:

Student studentOne = new Student.Builder("Andrue", "Booble", /*Date variable here*/);

У меня проблема с компилятором:

Ошибка: (24, 30) java: несовместимые типы: course_2.Student.Builder не может быть преобразован в course_2.Student

Может ли кто-нибудь помочь мне понять, почему это происходит и как я могу это решить? Спасибо!


person Leneron    schedule 08.07.2015    source источник
comment
По той же причине, по которой вы не можете сделать int i = "hello";.   -  person user253751    schedule 08.07.2015
comment
^ очень информативный и глубокий комментарий.   -  person Leneron    schedule 08.07.2015


Ответы (2)


Вам нужно добавить следующее к вашему Builder:

        public Student build(){
            return new Student(this);
        }

И назовите это так:

    Student studentOne = new Student.Builder("Andrue", "Booble", null).build();
person OldCurmudgeon    schedule 08.07.2015
comment
@OldCurmudgeon Можете ли вы помочь с моим вопросом здесь. Не могу понять, как правильно это сделать? - person john; 06.12.2016

new Student.Builder("Andrue", "Booble", /*Date variable here*/); возвращает объект строителя, а не студента.

В вашей фабрике отсутствует метод create, который вызывает конструктор Student

это должно выглядеть так

 public Student create(){
 return new student (this);
 }

и быть реализованным внутри класса Builder

теперь, если вы хотите создать Student, вы звоните

Student studentOne = new Student.Builder("Andrue", "Booble", /*Date variable here*/).create();
person user902383    schedule 08.07.2015