Created
July 15, 2024 11:01
-
-
Save Tanmay451/3d09d38a6023788ea8f201823abf6d45 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Car { | |
private String name; | |
private Integer year; | |
private String color; | |
@Override | |
public String toString() { | |
return "Car{" + | |
"name='" + name + '\'' + | |
", year=" + year + | |
", color='" + color + '\'' + | |
'}'; | |
} | |
public Car(CarBuilder cb){ | |
this.name = cb.name; | |
this.year = cb.year; | |
this.color = cb.color; | |
} | |
public static class CarBuilder{ | |
private String name; | |
private Integer year; | |
private String color; | |
public CarBuilder(String name) { | |
this.name = name; | |
} | |
public CarBuilder setYear(Integer year){ | |
this.year = year; | |
return this; | |
} | |
public CarBuilder setColor(String color){ | |
this.color = color; | |
return this; | |
} | |
public Car build(){ | |
return new Car(this); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Main { | |
public static void main(String[] args) { | |
Car.CarBuilder cb = new Car.CarBuilder("car1"); | |
Car car1 = cb.build(); | |
System.out.println(car1); | |
Car car2 = cb.setColor("red").build(); | |
System.out.println(car2); | |
Car car3 = cb.setYear(2024).build(); | |
System.out.println(car3); | |
} | |
} | |
// Car{name='car1', year=null, color='null'} | |
// Car{name='car1', year=null, color='red'} | |
// Car{name='car1', year=2024, color='red'} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment