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
- What is constructor?
- Why default constructor is used?
- Does constructor return any value in java?
- Is constructor inherited in java?
- Can you make a constructor final in java?
- Difference between constructor and method in java?
- How to copy values from one object to another java?
- How to overload constructor in java?
- can you create an object without using new operator in java?
- What is constructor chaining in java?
- Why we use parameterized constructor in java?
- Can we call subclass constructor from superclass constructor?
- What happens if you keep return type for a constructor?
- What is the use of private constructor in java?
- Can a constructor call another constructor java?