Default constructor vs Parametrized constructor: In this article, we will list the difference between the default constructor and parameterized constructor in Java. Let us detail out the difference between the Default constructor v/s Parametrized constructor in the tabular form below.
Default Constructor vs Parametrized Constructor
| Default constructor | Parameterized constructor |
| A constructor which takes no arguments is known as the default constructor | A constructor which takes one or more arguments is known as parameterized constructor |
| The compiler inserts a default no-arg constructor after compilation if there is no explicit constructor defined in a class | When the parameterized constructor is defined in a class, then the programmer needs to define default no-arg constructor explicitly if required |
| No need to pass any parameters while constructing new objects using the default constructor | At least one or more parameters need to be passed while constructing new objects using argument constructors |
| A default constructor is used for initializing objects with the same data | Whereas parametrized constructor is used to create distinct objects with different data |
Example for Default constructor vs 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
Your comments/suggestions/feedback of Interview Questions in this post will help a lot of people in the QA community for helping them in cracking the interviews.