Argument errorr in Java Nested Builder Pattern - java

I am learning the Java Builder Pattern from Section 6.1 (Builder Pattern Example) at: https://www.baeldung.com/creational-design-patterns#factory-method
But after I run my own code, it shows the error, wonder if could anyone help to point out where is wrong? Thanks a lot in advance.
class Test {
public static void main(String[] args) {
BankAccount newAccount = new BankAccount.BankAccountBuilder("Jon", "22738022275").withEmail("jon#example.com").wantNewsletter(true).build();
System.out.print(newAccount);
}
}
public class BankAccount {
private String name;
private String accountNumber;
private String email;
private boolean newsletter;
// constructors/getters
public static class BankAccountBuilder {
private String name;
private String accountNumber;
private String email;
private boolean newsletter;
public BankAccountBuilder(String name, String accountNumber) {
this.name = name;
this.accountNumber = accountNumber;
}
public BankAccountBuilder withEmail(String email) {
this.email = email;
return this;
}
public BankAccountBuilder wantNewsletter(boolean newsletter) {
this.newsletter = newsletter;
return this;
}
public BankAccount build() {
return new BankAccount(this);
}
}
}

You are missing the private constructor, something like:
//The constructor that takes a builder from which it will create the object
//the access to this is only provided to builder
private BankAccount(BankAccountBuilder builder) {
this.name = builder.name;
this.accountNumber = builder.accountNumber;
this.email = builder.email;
this.newsletter = builder.newsletter;
}
I assume the article leaves it to the reader in the section that says // constructors/getters on the code.
In addition, not completely related but the System.out.print you have will not print the object but its reference, you don't have a toString() method.

This is probably a duplicate but you just didn't declare a constructor. This code needs a constructor:
public class BankAccount {
private String name;
private String accountNumber;
private String email;
private boolean newsletter;
// constructors/getters
// ** you didn't put anything here **
So just add a constructor
// constructors/getters
private BankAccount( BankAccountBuilder b ) {
// initialize your class here
}

Related

Java Builder Object Printing Null

I have created a Person, class and a Professor class that both use the Builder Pattern to create objects. The Professor class takes a Person object as an argument in its constructor. I am trying to use both classes together, but when I attempt to print out a professor, get the following output: null null (instead of Bob Smith).
Here's what I tried so far:
Person:
public class Person {
private String firstname;
private String lastname;
private int age;
private String phoneNumber;
private String emailAddress;
private char gender;
public Person(){}
// builder pattern chosen due to number of instance fields
public static class PersonBuilder {
// required parameters
private final String firstname;
private final String lastname;
// optional parameters
private int age;
private String phoneNumber;
private String emailAddress;
private char gender;
public PersonBuilder(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
public PersonBuilder age(int age) {
this.age = age;
return this;
}
public PersonBuilder phoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
return this;
}
public PersonBuilder emailAddress(String emailAddress) {
this.emailAddress = emailAddress;
return this;
}
public PersonBuilder gender(char gender) {
this.gender = gender;
return this;
}
public Person build() {
return new Person(this);
}
}
// person constructor
private Person(PersonBuilder builder) {
this.firstname = builder.firstname;
this.lastname = builder.lastname;
this.age = builder.age;
this.phoneNumber = builder.phoneNumber;
this.emailAddress = builder.emailAddress;
this.gender = builder.gender;
}
#Override
public String toString() {
return this.firstname + " " + this.lastname;
}
}
Here's the Professor class:
package com.example.hardcodedloginform;
import java.util.List;
public class Professor extends Person{
private Person professor;
private double salary;
private String courseTaught;
private List<Student> students;
private int professorID;
public static class ProfessorBuilder {
// required fields
private Person professor;
private int professorID;
// optional fields
private double salary;
private String courseTaught;
private List<Student> students;
public ProfessorBuilder(Person professor, int professorID) {
this.professor = professor;
this.professorID = professorID;
}
public ProfessorBuilder salary(double salary) {
this.salary = salary;
return this;
}
public ProfessorBuilder courseTaught(String courseTaught) {
this.courseTaught = courseTaught;
return this;
}
public ProfessorBuilder students(List<Student> students) {
this.students = students;
return this;
}
public Professor build() {
return new Professor(this);
}
}
private Professor(ProfessorBuilder builder) {
this.salary = builder.salary;
this.courseTaught = builder.courseTaught;
this.students = builder.students;
}
#Override
public String toString() {
return "" + super.toString();
}
}
And here is the Main class where I try to print out a professor object:
public class Main {
public static void main(String[] args) {
Person profBobs = new Person.PersonBuilder("Bob", "Smith")
.age(35)
.emailAddress("bob.smith#SNHU.edu")
.gender('M')
.phoneNumber("818-987-6574")
.build();
Professor profBob = new Professor.ProfessorBuilder(profBobs, 12345)
.courseTaught("MAT101")
.salary(15230.01)
.build();
System.out.println(profBob);
}
}
I would like the printout in the console to be "Bob Smith", but what I am seeing is: null null. I checked and found that the Person object profBobs is, in fact, created properly and does print out the name "Bob Smith" when I attempt to print it the same way. I don't know why my Professor prints: null null.
Your Professor constructor fails to initialise any member fields of its base class.
There are multiple ways to solve this. One solution has ProfessorBuilder extend PersonBuilder:
public class Professor extends Person {
// Remove the `person` field! A professor *is-a* person, it does not *contain* it.
private double salary;
private String courseTaught;
private List<Student> students;
private int professorID;
public static class ProfessorBuilder extends Person.PersonBuilder {
// required fields
private int professorID;
// optional fields
private double salary;
private String courseTaught;
private List<Student> students;
public ProfessorBuilder(Person professor, int professorID) {
super(professor);
this.professorID = professorID;
}
// …
}
private Professor(ProfessorBuilder builder) {
super(builder);
this.salary = builder.salary;
this.courseTaught = builder.courseTaught;
this.students = builder.students;
}
}
For this to work you also need to mark the Person constructor as protected rather than private.
Furthermore, your Professor.toString method implementation made no sense: it essentially just called the base class method, so there’s no need to override it. And prepending the empty string does nothing.

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.
EDIT:
now it seems to be okay, but how do i use it with the builder inside the main?
this was the code i used
main:
Person person3 = new Person.PersonBuilder("Julliete", "Kaplan" )
.status(); // what should i write here to set the status?
person class
public class Person
{
private final String name;
private final String lastname;
private final int age;
//My enum im trying to use
private Status status;
public 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;
}
//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;
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;
}
}
Don't define another Status enum inside the builder: reuse the one defined in the Person class.
Otherwise, you've got to map from instances of PersonBuilder.Status to instances of Person.Status: they are entirely separate types.
Currently this mapping is trivial: you can use Person.Status.valueOf(personBuilderStatus.name()) - but you have to ensure that you update both at the same time to have identical values (or at least that PersonBuilder.Status maps to a subset of Person.Status), which is an unnecessary maintenance burden going forwards.

create unique id without using constructure and setters

class person {
private int id ;
private String name;
private boolean gender;
public person() {
}
public AtomicLong getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
}
I want to create unique id in this class without using constructors and setters.
To construct a person instance, the field initializer will be copied into the constructor. Assuming that's okay, you could use an AtomicInteger and something like,
private static AtomicInteger ai = new AtomicInteger(0);
private int id = ai.incrementAndGet();
you could add:
private static int ID_GENERATOR = 0;
then, in the constructor, you will use:
public person() {
id = ID_GENERATOR++;
}

How can I access the member variable of class A outside the method, that has been instantiated in other class?

Question before editing: How can I delegate the initialization process of too many member variable of class A inside class B and C and still use the value inside class A?
Note: (class B and C is present inside class A)
The main objective is to reduce too many member variables present in class A.
I am following whats it is said in this post [1]: https://stackoverflow.com/a/16994754/2018343
code would be like is
UPDATED:
public class A{ // start of class A
public int a;
int b;
public int c;
int d;
int x;
int g;
B bObject; //instance of class B
C cObject; //instance of class B
A(){ /**Constructor*/
bObject = new B(3,4);
cObject = new C(5,6);
} /*
*There is an error in eclipse after this closing bracket
*"Syntax error on token "}", { expected after this token"
*/
/**
* My end goal: I need to Use the initialized variables after the constructor
*/
public void yui(){
if(true){ // variables a and c
// System.out.println("A is greater");
x=a;
g=c;
}
} /**
* Syntax error on token "}", { expected after this token */
if(x<g){ // variables x and g
System.out.println("A is greater");
}
class B{ //Note: This class is inside class A
B(int val1, int val2){
a=val1;
b=val2;
}
}
class C{ // //Note: This class is inside class A
C(int val3,int val4){
c= val3;
d= val4;
}
}
public static void main(String[] args){
A a = new A();
a.yui();
}
} // end of class A
I am really looking for delegating the initialization process of too many variables to other child class and main thing is use that initialized variable value in the subsequent lines of code in master class.
Seek your help!
You can use the Builder pattern to make the initialization more user friendly.
A nice example that was taken from here:
public class User {
private final String firstName; // required
private final String lastName; // required
private final int age; // optional
private final String phone; // optional
private final String address; // optional
private User(UserBuilder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.age = builder.age;
this.phone = builder.phone;
this.address = builder.address;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getPhone() {
return phone;
}
public String getAddress() {
return address;
}
public static class UserBuilder {
private final String firstName;
private final String lastName;
private int age;
private String phone;
private String address;
public UserBuilder(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public UserBuilder age(int age) {
this.age = age;
return this;
}
public UserBuilder phone(String phone) {
this.phone = phone;
return this;
}
public UserBuilder address(String address) {
this.address = address;
return this;
}
public User build() {
return new User(this);
}
}
}
and how to use it:
public User getUser() {
return new
User.UserBuilder("Jhon", "Doe")
.age(30)
.phone("1234567")
.address("Fake address 1234")
.build();
}

What's wrong with my builder pattern?

I have a problem in realisation of Builder pattern.
I have 2 classes:
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;
}
}
The problem is when I'm trying to call a Builder from my client code:
Student studentOne = new Student.Builder("Andrue", "Booble", /*Date variable here*/);
I'm getting a compiler problem :
Error:(24, 30) java: incompatible types: course_2.Student.Builder
cannot be converted to course_2.Student
Can somebody help me with understanding, why does this happen and how I can solve it? Thanks!
You need to add the following to your Builder:
public Student build(){
return new Student(this);
}
And call it like this:
Student studentOne = new Student.Builder("Andrue", "Booble", null).build();
new Student.Builder("Andrue", "Booble", /*Date variable here*/); returns you builder object not student.
Your factory is missing method create which invoke Student constructor
it should looks like this
public Student create(){
return new student (this);
}
and be implemented inside Builder class
now if you want to create Student, you call
Student studentOne = new Student.Builder("Andrue", "Booble", /*Date variable here*/).create();

Categories

Resources