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

Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki