Parameterized constructor in java

Parameterized constructor

A constructor with one or more parameters is called as parameterized constructor.

Why parameterized constructor is used?

Parameterized constructor is used to provide the initial values to the object properties (initial state of object). By use of parameterized constructor different objects can be initialize with different data member values or states.

Example

/**
 * This program is used to show the use of parameterized constructor.
 * @author w3schools
 */
public class ParameterizedConstructor {
                int num;
                String str;
 
                ParameterizedConstructor (int n, String s){
                      System.out.println("Parameterized Constructor called.");
                      num = n;
                      str = s;
                }
 
                public static void main(String args[]){
                     //constructor call
                     ParameterizedConstructor object = new ParameterizedConstructor (10, "w3schools");
 
                     //print values of object properties
                     System.out.println("num = " + object.num);
                     System.out.println("str = " + object.str);
                }
}

Output

Parameterized Constructor called.
num = 10
str = w3schools

Java interview questions on constructor