Skip to content

Instantly share code, notes, and snippets.

@bhawna94
Created July 13, 2020 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhawna94/7341e898ef3136d0d4086293307d5056 to your computer and use it in GitHub Desktop.
Save bhawna94/7341e898ef3136d0d4086293307d5056 to your computer and use it in GitHub Desktop.
class Person {
private final String firstName; // required
private final int age;
private final String phone;
private Person(PersonBuilder builder) {
this.firstName = builder.firstName;
this.age = builder.age;
this.phone = builder.phone;
}
public String getFirstName() {
return firstName;
}
public int getAge() {
return age;
}
public String getPhone() {
return phone;
}
@Override
public String toString() {
return "Person{" +
"firstName='" + firstName + '\'' +
", age=" + age +
", phone='" + phone + '\'' +
'}';
}
//Builder class
public static class PersonBuilder
{
private final String firstName;
private int age;
private String phone;
public PersonBuilder(String firstName) {
this.firstName = firstName;
}
public PersonBuilder age(int age) {
this.age = age;
return this;
}
public PersonBuilder phone(String phone) {
this.phone = phone;
return this;
}
public Person build() {
return new Person(this);
}
}
public static void main(String[] args) {
//Creating an Object
Person person = new Person.PersonBuilder("Bhawna")
.age(23)
.phone("1234567")
.build();
System.out.println(person);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment