Default Constructor in Java

Default constructor is automatically created by the compiler if we do not declare any constructor. The features of default constructor are :

  1. Created by the compiler.
  2. Access specifier of default constructor is public.
  3. Default constructor do not have any arguments.
  4. A default constructor contains initialization of all the instance variables of the class. These variables are initialized with their default values. Example :-
    • String, Integer and all other objects with null value.
    • int, long and short with 0
    • double and float with 0.0
    • boolean with false.

Let us look at an example to understand default constructor:

public class Tech4Humans {
	public static void main(String[] args) {
		//calling of default constructor with 'TestA()'
		TestA obj = new TestA();
		obj.printVariables();
	}
}

//no constructor has been created
class TestA{		
	int age;
	String name;		
		
	void printVariables() {
		System.out.println("name = "+name);
		System.out.println("age = "+age);
	}
}

Output

name = null
age = 0

As you can see in the above code we have not created any constructor in our class TestA, still instance variables age and name has been initialized to their default values. This is because compiler automatically creates a default constructor with default values of its instance variables.

Let us now learn about Parameterized Constructors.

Leave a Comment