0

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.

error

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


Parting
  • 186
  • 1
  • 8
  • Duplicate -ish posts: notice that since you didn't declare a constructor, you have only the default constructor: https://stackoverflow.com/questions/4488716/java-default-constructor – markspace Sep 03 '22 at 18:02
  • Private constructor: https://stackoverflow.com/questions/2816123/can-a-constructor-in-java-be-private – markspace Sep 03 '22 at 18:03

2 Answers2

1

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
    }
markspace
  • 10,621
  • 3
  • 25
  • 39
1

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.

fjavierm
  • 151
  • 3