Write a Java program to Implement constructor overloading


This is an example of constructor overloading in Java. The class Demo has two constructors - a default constructor and a parameterized constructor that takes two integer arguments.

The Constructor_Overloading class creates two objects of the Demo class using both constructors. The first object is created using the default constructor, while the second object is created using the parameterized constructor with values 300 and 400.

Both objects are then printed using the printValues() method, which prints the values of the num1 and num2 instance variables for each object. The first object will have values of 100 and 200 for num1 and num2 respectively, while the second object will have values of 300 and 400.

Source Code

class Constructor_Overloading
{
	public static void main(String args[])
	{
		Demo o1 = new Demo();
		Demo o2 = new Demo(300, 400);
 
		o1.printValues();
		o2.printValues();
	}
}
class Demo
{
	int num1;
	int num2;
 
	Demo()
	{
		num1 = 100;
		num2 = 200;
	}
 
	Demo(int n1, int n2)
	{
		num1 = n1;
		num2 = n2;
	}
 
	void printValues()
	{
		System.out.println("Number 1 : " + num1);
		System.out.println("Number 2 : " + num2);
	}
}

Output

Number 1 : 100
Number 2 : 200
Number 1 : 300
Number 2 : 400