CodesJava

Easy learning with example program codes

how to overload constructor in java?


The process of defining more than one constructor with different parameters in a class is known as constructor overloading. Parameters can differ in number, type or order.

Example

/**
 * This program is used to show the use of constructor overloading.
 * @author CodesJava
 */
public class ConstructorExample5 {
       int num;
       boolean isStudent;
       String str;
 
 
       //One argument constructor
       ConstructorExample5(boolean boolean1){
       System.out.println("One argument constructor called.");
          isStudent = boolean1;
       }               
 
       //Two argument constructor
       ConstructorExample5(int n, String s){
        System.out.println("Two argument constructor called.");
        num = n;
        str = s;
       }    
 
       //Three argument constructor
       ConstructorExample5(boolean boolean1, int n, String s){
         System.out.println("Three argument constructor called.");
         isStudent = boolean1;
         num = n;
         str = s;
        }
       public static void main(String args[]){
         //one argument constructor call
         ConstructorExample5 obj1 = new ConstructorExample5(true);
 
         //print values of object properties.
         System.out.println("isStudent = " + obj1.isStudent);
         System.out.println("num = " + obj1.num);
         System.out.println("str = " + obj1.str); 
 
         //two argument constructor call
         ConstructorExample5 obj2 = 
               new ConstructorExample5(10, "CodesJava");
 
          //print values of object properties.
          System.out.println("isStudent = " + obj2.isStudent);
          System.out.println("num = " + obj2.num);
          System.out.println("str = " + obj2.str);
 
          //three argument constructor call
          ConstructorExample5 obj3 = new
          ConstructorExample5(false, 20, "CodesJava.com");
 
          //print values of object properties.
          System.out.println("isStudent = " + obj3.isStudent);
          System.out.println("num = " + obj3.num);
          System.out.println("str = " + obj3.str);
        }
}

Output

isStudent = false
num = 20
str = CodesJava.com

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