Java: Default constructor v/s Parametrized constructor

In this article, we will list the difference between default constructor and parametrized constructor in Java

Before moving ahead with the differences, read the detailed concepts about java constructor, default constructor and parametrized constructor in the following articles

 

Let us detail out difference between Default constructor v/s Parametrized constructor in tabular form below,

 

 Sr. No.  Default constructor  Parametrized constructor
1 A constructor which takes no arguments is known as default constructor A constructor which takes one or more arguments is known as parametrized constructor
2 Compiler inserts a default no-arg constructor after compilation, if there is no explicit constructor defined in class When parametrized constructor are defined in class, then programmer needs to define default no-arg constructor explicitly if required
3 No need to pass any parameters while constructing new objects using default constructor At least one or more parameters needs to be passed while constructing new objects using argument constructors
4 Default constructor is used to initialize objects with same data Whereas parametrized constructor are used to create distinct objects with different data
5 Read more about Default Constructor here Read more about Parametrized Constructor here

 

Example for Default constructor v/s Parametrized constructor

Employee.java

package in.bench.resources.constructor.example;

public class Employee {

	// member variables
	int employeeId;
	String employeeName;
	String employeeOrg;

	// default constructor
	Employee() {

		// an implicit super() constructor call to java.lang.Object is always present until we specify explicitly
		System.out.println("Employee class >> Inside default constructor");
		this.employeeOrg = "Google Corporation Inc.";
	}

	// parametrized constructor with 2 argument (String, int)
	Employee(String name, int id) {

		this(); // to invoke another constructor from same class, this() constructor is used

		System.out.println("Employee class >> Inside parametrized constructor with 1 argument (String)");
		this.employeeName = name;
		this.employeeId = id;
	}

	// display() method
	void displayEmployeeInfo() {
		System.out.println("\nEmployee details:  \n\nOrgnaization: " + employeeOrg + "\nId: " + employeeId + "\nName: " + employeeName + "\n");
	}

	public static void main(String args[]) {
		Employee emp = new Employee("Rahul Dravid", 19);
		emp.displayEmployeeInfo();
	}
}

Output:

Employee class >> Inside default constructor
Employee class >> Inside parametrized constructor with 1 argument (String)

Employee details:  

Orgnaization: Google Corporation Inc.
Id: 19
Name: Rahul Dravid

 

 

References:

https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

 

Read Also:

Happy Coding !!
Happy Learning !!