gpt4 book ai didi

java - 我的构建器模式有什么问题?

转载 作者:行者123 更新时间:2023-12-01 22:14:49 25 4
gpt4 key购买 nike

我在实现Builder模式时遇到问题。我有两个类:

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;
}
}

问题是当我尝试从客户端代码调用构建器时:

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

我遇到编译器问题:

Error:(24, 30) java: incompatible types: course_2.Student.Builder cannot be converted to course_2.Student

有人可以帮助我理解为什么会发生这种情况以及如何解决它吗?谢谢!

最佳答案

您需要将以下内容添加到您的Builder中:

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

并这样调用它:

    Student studentOne = new Student.Builder("Andrue", "Booble", null).build();

关于java - 我的构建器模式有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31290378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com