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 W3spoint
 */
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, "W3spoint");
 
                     //print values of object properties
                     System.out.println("num = " + object.num);
                     System.out.println("str = " + object.str);
                }
}

Output

Parameterized Constructor called.
num = 10
str = W3spoint

Java interview questions on constructor

Please Share