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.
class Car {
String name;
//parameterize constructor
public Car(String name) {
this.name = name;
}
void run(){
System.out.println(name+" Car is running...");
}
}
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
/*
* parametrized constructor java example
*/
class Car {
String name;
//parameterize constructor
public Car(String name) {
this.name = name;
}
void run(){
System.out.println(name+" Car is running...");
}
}
public class Sample {
public static void main(String[] args) {
//We we crate an object, the consturctor of the
//class will be called automatically.
Car maruti = new Car("Maruti");
maruti.run();
Car honda = new Car("honda");
honda.run();
}
}
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:
/*
* Example of Multiple parameters in constructor in java
*/
class Car {
String name;
String color;
// parameterize constructor
public Car(String name, String color) {
this.name = name;
this.color = color;
}
void run() {
System.out.println(color + " " + name + " " + " Car is running...");
}
}
public class Sample {
public static void main(String[] args) {
// We we crate an object, the consturctor of the
// class will be called automatically.
Car maruti = new Car("Maruti", "Red");
maruti.run();
Car honda = new Car("Honda", "Black");
honda.run();
}
}
Output:
Red Maruti Car is running…
Black Honda Car is running…