The way of defining multiple constructor with different arguments in a specified class is called constructor overloading. Parameters can differ in type, number or order.
Example
/** * This program is used to show the use of constructor overloading. * @author W3spoint */ public class ConstructorOverload { int rollNo; boolean isStudent; String name; //One argument constructor ConstructorOverload(boolean isStudent ){ System.out.println("One argument constructor called."); this.isStudent = isStudent ; } //Two argument constructor ConstructorOverload (int rollNo, String name){ System.out.println("Two argument constructor called."); this.rollNo = rollNo; this.name = name; } //Three argument constructor ConstructorOverload (boolean isStudent, int rollNo, String name){ System.out.println("Three argument constructor called."); this.isStudent = isStudent ; this.rollNo = rollNo; this.name = name; } public static void main(String args[]){ //one argument constructor call ConstructorOverload obj1 = new ConstructorOverload(true); //print values of object properties. System.out.println("isStudent = " + obj1.isStudent); System.out.println("Roll No = " + obj1.rollNo); System.out.println("Name = " + obj1.name); //two argument constructor call ConstructorOverload obj2 = new ConstructorOverload(11, "Jai"); //print values of object properties. System.out.println("isStudent = " + obj2.isStudent); System.out.println("Roll No = " + obj2.rollNo); System.out.println("Name = " + obj2.name); //three argument constructor call ConstructorOverload obj3 = new ConstructorOverload(true, 22, "Roxy"); //print values of object properties. System.out.println("isStudent = " + obj3.isStudent); System.out.println("Roll No = " + obj3.rollNo); System.out.println("Name = " + obj3.name); } } |
Output
One argument constructor called. isStudent = true Roll No = 0 Name = null Two argument constructor called. isStudent = false Roll No = 11 Name = Jai Three argument constructor called. isStudent = true Roll No = 22 Name = Roxy |
Java interview questions on constructor
- Default constructor
- 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?
- Constructor chaining in java
- 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?
Please follow and like us: