Multiple Constructors in Java with Example

(Last Updated On: February 27, 2019)

Learn multiple constructors in java with example. A class can have multiple constructors with different types of arguments and different number of arguments.

For example, in below Car class we have three constructors written for Car class i.e. with empty, one parameter and two parameters.

 

 

We know that when a class object is created, the constructor is called automatically. [ Have a look on this constructor example in java, where on creation of object of class Car, the Car constructor is automatically invoked. Also, recommend to read Simple parameterized constructor in java for better understanding.],

Similarly, when we create class object with parameters then the matching constructors get called.

For example,

If you create an object of Car with 1 argument, the constructor having single parameter will be called automatically. For example,

Car Maruti = new Car(“maruti); // 1 String argument is passed during creation of object.

So, it will look for a constructor with 1 string parameter i.e. public Car(String name)

 

If you create object with 2 arguments, the constructor having 2 parameters will be called automatically. for example,

Car Maruti = new Car(“Maruti”, double price); // 2 arguments i.e. String and double arguments are passed during creation of object.

So, it will look for a constructor with 2 parameters e.g. public Car(String name, double price).

 

Here is complete example that demonstrate the multiple constructors uses in java program.

Example of Multiple constructors in Java

 

Output:
1 parameters constructor is called
Car name :Maruti
Maruti Car is running…
1 parameters constructor is called
Car name :honda
honda Car is running…
2 parameters constructor is called
Car name :Maruti, price:400000.0
Maruti Car is running…
2 parameters constructor is called
Car name :honda, price:700000.0
honda Car is running…

 

Exercise:

Create a class named Pet. Create two constructors i.e. empty constructor and constructor with a parameter “name” of String type.

Solution: