A constructor initializes objects when they're created.
public class Car {
String brand;
// Constructor
public Car() {
brand = "Unknown";
}
}
public class Car {
String brand;
String color;
public Car(String brand, String color) {
this.brand = brand;
this.color = color;
}
}
// Usage
Car myCar = new Car("Toyota", "Red");
this KeywordRefers to the current object:
this.brand = the object's brand fieldbrand = constructor parameterInteractive Visualization