A Constructor is used to initialize an object. A constructer is nothing but a special function within a class which has same name as that of the class and does not return any value.
DEFAULT CONSTRUCTOR/NO ARG CONSTRUCTOR
public class car {
car(){
//initializing code
}
}
The above code snippet creates a class car and has a constructer method which will initialize the class to form an instance. A constructer with no parameters is called default constructor. You can create only one no-arg constructor in a class. If you do not create a default constructor then Java will create one for you implicitly. There will be slight change in the behavior but we will come back to it later.
PARAMETERIZED CONSTRUCTOR
public class car {
String make;
String model;
car(String make,String model){
this.make = make;
this.model = model;
}
}
The above code snippet is an example of a parameterized constructor. As the name suggests, it is a constructor with parameters. If you have created a parameterized constructor then Java will not create a default constructor for you. This is where the behavior changes for the implicit default constructor. You can create multiple parameterized constructors in a class, however no two parameterized constructors can have same signature. By signature here I mean that no two constructors can have same type of parameter in same order.
Below code will result into a compilation error because the signature for both constructors are same.
public class car {
car(String make, String model){
//initializing code
}
car(String model, String Make){
//initializing code
}
}