Created
January 5, 2024 13:19
-
-
Save isaacssemugenyi/aaa6d883ca958b9cd3d95007f235f1ea to your computer and use it in GitHub Desktop.
This file contains 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
package builder; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class Car { | |
private String make; | |
private String name; | |
private String color; | |
private int model; | |
private List<String> countriesPresent = new ArrayList<>(); | |
@Override | |
public String toString() { | |
return String.format( | |
"{ make = %s, name = %s, color = %s, model = %s , countriesPresent = %s }", | |
make, | |
name, | |
color, | |
model, | |
countriesPresent | |
); | |
} | |
private Car(Builder builder){ | |
this.make = builder.make; | |
this.name = builder.name; | |
this.color = builder.color; | |
this.model = builder.model; | |
this.countriesPresent = builder.countriesPresent; | |
} | |
public static class Builder { | |
private String make; | |
private String name; | |
private String color; | |
private int model; | |
private List<String> countriesPresent = new ArrayList<>(); | |
public Builder make(String make){ | |
this.make = make; | |
return this; | |
} | |
public Builder name(String name){ | |
this.name = name; | |
return this; | |
} | |
public Builder color(String color){ | |
this.color = color; | |
return this; | |
} | |
public Builder model(int model){ | |
this.model = model; | |
return this; | |
} | |
public Builder addCountry(String countriesPresent){ | |
this.countriesPresent.add(countriesPresent); | |
return this; | |
} | |
public Car build(){ | |
return new Car(this); | |
} | |
} | |
} |
This file contains 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
package builder; | |
public class Main { | |
public static void main(String[] args){ | |
Car car = new Car.Builder() | |
.make("Ford") | |
.name("Mastunga") | |
.color("Red") | |
.model(2023) | |
.addCountry("Kenya") | |
.addCountry("Uganda") | |
.build(); | |
System.out.println(car); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment