Constructor Overloading Example Java Program


Definition

A constructor in a class is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables. A constructor resembles an instance method, but it differs from a method in that it has no explicit return type. Constructors often have the same name as the declaring class.

Syntax

NameOfClass() {
    //Statements
    }
NameOfClass(Parameters) {
    //Statements
    }
ParentClass{
	//Statements
	}

Constructor Overloading Example Program

class ConstructorOverloading{
	ConstructorOverloading(){
		System.out.println("1. " + "Constructor with no parameter.");
	}
	ConstructorOverloading(int p, int q){
		System.out.println("2. " + (p+q));
	}
	ConstructorOverloading(int p, int q, int r){
		System.out.println("3. " + (p+q+r));
	}
	ConstructorOverloading(int p, int q, float r){
		System.out.println("4. " + (p+q+r));
	}
	ConstructorOverloading(float r, int p, int q){
		System.out.println("5. " + (p+q+r));
	}
	public static void main(String []args){
		ConstructorOverloading obj = new ConstructorOverloading(10, 20);
		ConstructorOverloading obj1 = new ConstructorOverloading(10, 20, 30);
		ConstructorOverloading obj2 = new ConstructorOverloading();
		ConstructorOverloading obj3 = new ConstructorOverloading(10, 20, 4.5f);
		ConstructorOverloading obj4 = new ConstructorOverloading(7.8f, 10, 20);
	}
}

Sample Output

Output is:
2. 30
3. 60
1. Constructor with no parameter.
4. 34.5
5. 37.8