实现构建器模式时无法将字符串转换为构建器类错误。请让我知道我做错了什么以及哪里做错了。谢谢。
封装BuilderDesignPattern;
公共(public)类员工{
private final int id;
private String Name;
private String Address;
private Employee(EmployeeBuilder empB){
//此行类型不匹配时出现错误,无法将字符串转换为 Employee.EmployeeBuilder。
this.id = empB.getId();
this.Name = empB.getName();
this.Address = empB.getAddress();
}
public static class EmployeeBuilder{
private int id;
private String Name;
private String Address;
public EmployeeBuilder setId(int id) {
this.id = id;
return this;
}
public EmployeeBuilder setName(String name) {
Name = name;
return this;
}
public EmployeeBuilder setAddress(String address) {
Address = address;
return this;
}
public EmployeeBuilder getId() {
return this;
}
public EmployeeBuilder getName() {
return this;
}
public EmployeeBuilder getAddress() {
return this;
}
public Employee build(){
return new Employee(this);
}
}
}
最佳答案
你的 getter 是错误的,没有返回正确的字段。应该是这样的:
public int getId() {
return this.Id;
}
public String getName() {
return this.Name;
}
public String getAddress() {
return this.Address;
}
P.S.:在java中,有一个用小写字母命名字段的约定。
P.S.2:这不是一流的构建器,因为构建的类“了解”构建器。
关于java - 实现构建器模式时无法将字符串转换为构建器类错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55747079/