A constructor is also a method. But this is a special method. The constructor method is called when the object is initialized. It can be used for initialized the objects attributes.
Constructor can be non parameterized and also can be parameterized. Now let's see some examples of non-parameterized and parameterized constructors.
non-parameterized constructors
class Cars{
public String car_name;
// Constructor non parameterized
public Cars() {
this.car_name = "BMW";
}
}
parameterized constructors
class Cars{
public String car_name;
// Constructor parameterized
public Cars(String car_name) {
this.car_name = car_name;
}
}
Also We can use constructor overloading like method overloading.
class Cars{
public String car_name;
// Constructor parameterized
public Cars(String car_name) {
this.car_name = car_name;
}
public Cars() {
this.car_name = "Unknown";
}
}