Skip to content

Instantly share code, notes, and snippets.

@alexander-beaver

alexander-beaver/Car.java Secret

Created Jan 30, 2020
Embed
What would you like to do?
Example Builder
package com.alexbeaver.blog.testbuilder;
public class Car {
public String make;
public String model;
public Color color;
public int year;
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public static class Builder{
public String make;
public String model;
public Color color;
public int year;
public Builder withMake(String make){
this.make = make;
return this;
}
public Builder withModel(String model){
this.model = model;
return this;
}
public Builder withColor(Color color){
this.color = color;
return this;
}
public Builder withYear(int year){
this.year = year;
return this;
}
public Car build(){
Car car = new Car();
car.make = this.make;
car.model = this.model;
car.color = this.color;
car.year = this.year;
return car;
}
}
}
package com.alexbeaver.blog.testbuilder;
public enum Color {
WHITE,
BLACK,
BLUE,
RED
}
package com.alexbeaver.blog.testbuilder;
public class Main {
public static void main(String[] args) {
// write your code here
Car car = new Car.Builder()
.withMake("Honda")
.withModel("Civic")
.withColor(Color.WHITE)
.withYear(2020)
.build();
System.out.println(car.model);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.