Constructor in java is a special type of method that is used to initialize the object. Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.
Constructor name must be same as its class name and must have no explicit return type.
There are two types of constructors:
1. Default constructor (Non Parameterized constructor)
Default constructor provides the default values to the object like 0, null etc. depending on the type.
2. Parameterized constructor
A constructor that have parameters is known as parameterized constructor.
Parameterized constructor is used to provide different values to the distinct objects.
Constructor overloading used in Java in which a class can have no. of constructors that differ in parameter lists.The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.
class Car
{
int id;
String carname;
String brand;
int qty;
Car(int i,String n){
id = i;
carname = n;
}
Car(int i,String n,Str a){
id = i;
carname = n;
brand =a;
}
Car(int i,String n,Str a,int t){
id = i;
carname = n;
brand =a;
qty = t;
}
void display()
{
System.out.println(id+" "+carname+" "+brand+" "+qty);
}
public static void main(String args[]){
Car s1 = new Student5(101,"Alto");
Car s2 = new Student5(102,"Swift","Maruti",25);
Car s2 = new Student5(102,"Swift","Maruti");
s1.display();
s2.display();
s3.display();
}
}
Output:
101 Alto 0
102 Swift Maruti 25
102 Swift Maruti 0