How to do constructor overloading in Java
In object acquainted programming, a constructor is a special system of classes that initializes a newly created object of that type. A constructor is automatically called when an object is made. The constructor name should be the same as the class name.
Types of constructors
There are three main types of constructors:
- Default
- No-arg
- Parameterized
Constructor overloading
Constructor overloading is a concept in which we have more than one constructor with different parameters. Each constructor performs its own task.
public class Cars{String carname;int model;int mileage;Cars(){carname="BMW";model=2021;}Cars(String s,int i){carname=s;model=i;}Cars(String r, int y,int t){carname=r;model=y;mileage=t;}public static void main(String args[]){Cars c1=new Cars(); // calling with deafault constructorSystem.out.println("Default Constructor : ");System.out.println("Car Name : " +c1.carname +" "+"Car Model : " +c1.model);System.out.println();Cars c2=new Cars("Suzuki",2019); // calling with parameterized overloaded constructor;System.out.println("This is the Overloaded Constructor with two parameters : ");System.out.println("Car Name : " +c2.carname+" "+"Car Model : " +c2.model);System.out.println();Cars c3=new Cars("Suzuki",2020,20); // calling with parameterized overloaded constructor;System.out.println("This is the Overloaded Constructor with three parameters : ");System.out.println("Car Name : " +c3.carname+" "+"Car Model : " +c3.model+" "+"Mileage : "+c3.mileage);}}
-
In the code above, we implement constructor overloading.
-
The class and constructor are both named
Carsbecause the name of the constructor should be the same as the class name. -
We have a default constructor, a constructor with two parameters, and a constructor with three parameters.
-
A default constructor has no parameters.
-
A parameterized constructor has parameters to initialize some values.