Skip to content

Instantly share code, notes, and snippets.

@isaacssemugenyi
Last active January 9, 2024 10:07
Show Gist options
  • Save isaacssemugenyi/1d1f867d0f64e447077c061ad77dc988 to your computer and use it in GitHub Desktop.
Save isaacssemugenyi/1d1f867d0f64e447077c061ad77dc988 to your computer and use it in GitHub Desktop.
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<>();
public void setMake(String make) {
this.make = make;
}
public void setName(String name) {
this.name = name;
}
public void setColor(String color) {
this.color = color;
}
public void setModel(int model) {
this.model = model;
}
public void setCountriesPresent(List<String> countriesPresent) {
this.countriesPresent = countriesPresent;
}
@Override
public String toString() {
return String.format(
"{ make = %s, name = %s, color = %s, model = %s , countriesPresent = %s }",
make,
name,
color,
model,
countriesPresent
);
}
/**
* New Code added
*/
public Car(String make, String name, String color, int model, List<String> countriesPresent) {
this.make = make;
this.name = name;
this.color = color;
this.model = model;
this.countriesPresent = countriesPresent;
}
/**
* This no-args constructor is created by the compiler if no constructor is created (created only when we don't declare any constructor),
* Once a constructor is created, like the all args constructor above,
* Then, this constructor does not exist, so to keep the first section of using setter working,
* we create this constructor ourselves
*/
public Car(){}
}
package builder;
import java.util.List;
public class Main {
public static void main(String[] args){
Car car1 = new Car();
car1.setMake("Tesla");
car1.setName("Model X");
car1.setModel(2020);
car1.setColor("Blue");
car1.setCountriesPresent(List.of("USA", "Germany", "China"));
System.out.println("No args constructor --> "+car1);
Car car2 = new Car("Toyota", "Fortuner", "Grey", 2021, List.of("Canada", "South Korea", "Egypt"));
System.out.println("All Args Constructor --> "+ car2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment