Default constructor

If you want to customize how a class initializes its members or calls functions when an object of the class is created, you have to define a constructor. Standard constructors have no parameters.

If no constructors are declared in a class, the compiler automatically provides a default constructor. On the other hand, if a class declaration contains only parameterized constructors, no default constructor is generated, and the class file has no parameterless constructor at all.

Syntax

class ClassName {
	// default constructor
	ClassName() {

	}
}

Example 1

class Person {
	Person() {
		System.out.print("default constructor");
	}

	public static void main(String[] args) {
		Person p = new Person();
	}
}
Output
default constructor

Example 2

class Cube {
	int length, width, height;

	Cube() {
		length = 5;
		width = 2;
		height = 4;
	}

	int getVolume() {
		return length * width * height;
	}

	public static void main(String[] args) {
		Cube c = new Cube();

		System.out.print(c.getVolume());
	}
}
Output
40