Write a Java program to Implement default constructor


A default constructor is a constructor that is provided by the Java compiler if no constructor is explicitly defined in a class. It takes no arguments and initializes the instance variables with default values (0 for numeric types, false for boolean, and null for object types).

In this program, the class Demo has two instance variables n1 and n2 that are initialized to 10 and 20, respectively, in the default constructor. The printValues() method prints the values of these instance variables.

The main() method creates an object of Demo class and calls the printValues() method to print the values of the instance variables.

Source Code

class Default_Constructor
{
	public static void main(String args[])
	{
		Demo d = new Demo();
		d.printValues();
	}
}
class Demo
{
	int n1;
	int n2;
	Demo()
	{
		n1 = 10;
		n2 = 20;
	}
	void printValues()
	{
		System.out.println("Number 1 : " + n1);
		System.out.println("Number 2 : " + n2);
	}
}

Output

Number 1 : 10
Number 2 : 20