Parameterized Constructor in Java

(Last Updated On: February 26, 2019)

Learn parameterized constructor in java with example in simple steps. Class constructors can also have parameters and receives arguments, the same way as class methods have parameters.

For example, in below Car class, a parameterized constructor “public Car(String name)” is defined, that takes 1 string argument.

 

You can read an example given in java constructor tutorial first in which, we have empty constructor e.g. Car() which was invoked on creating object like Car Maruti = new Car();

In the given parameterized constructor example above,

Now lets say we want to give name to cars, for example Maruti and Honda etc. So how can we do that. in previous example we have not given name.

we know that when we create an object of the class in java, the constructor get called automatically. So, we can create a parameterize constructor, where we can set the name of the car.

This program now prints the output as below

Maruti Car is running…
honda Car is running…

Parameterized constructor java example

 

 

Multiple parameters in constructor in java

A constructor can have multiple number of arguments. For example, in below Car class there are two arguments i.e. public Car(String name,String color).

When you create object of class with two arguments like below, it will automatically call the constructor.

Car maruti = new Car(“Maruti”,”red”);

 

Java Code:

 

Output:
Red Maruti Car is running…
Black Honda Car is running…