CodesJava

Easy learning with example program codes

why we use parameterized constructor in java?


Parameterized constructor

A constructor with one or more arguments is known as parameterized constructor.

Why parameterized constructor is used?

Parameterized constructor is used to provide values to the object properties. By use of parameterized constructor different objects can be initialize with different states.

Example

/**
 * This program is used to show the use of parameterized constructor.
 * @author CodesJava
 */
public class ConstructorExample3 {
                int num;
                String str;
 
                ConstructorExample3(int n, String s){
                      System.out.println("Constructor called.");
                      num = n;
                      str = s;
                }
 
                public static void main(String args[]){
                     //constructor call
                     ConstructorExample3 obj1 = 
                          new ConstructorExample3(10, "CodesJava");
 
                     //print values of object properties
                     System.out.println("num = " + obj1.num);
                     System.out.println("str = " + obj1.str);
                }
}
<h2>Output</h2>
<pre lang="java">
Constructor called.
num = 10
str = CodesJava

Java interview questions on main method



Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap