In this article, we will list the difference between default constructor and parameterized constructor in Java
Before moving ahead with the differences, read the detailed concepts about java constructor, default constructor and parameterized constructor in the following articles
Let’s detail out difference between Default constructor v/s Parameterized constructor in tabular form below,
Sr. No. | Default constructor | Parameterized constructor |
1 | A constructor which takes no arguments is known as default constructor | A constructor which takes one or more arguments is known as parameterized constructor |
2 | Compiler inserts a default no-arg constructor after compilation, if there is no explicit constructor defined in class | When parameterized 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 parameterized constructor are used to create distinct objects with different data |
5 | Read more about Default Constructor here | Read more about Parameterized Constructor here |
Example for Default constructor v/s Parameterized constructor
Employee.java
package in.bench.resources.constructor.example;
public class Employee {
// 1. member variables
int employeeId;
String employeeName;
String employeeOrg;
// 2. 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");
// initialize
this.employeeOrg = "Google Corporation Inc.";
}
// 3. parameterized-constructor with 2-argument (String, int)
Employee(String name, int id) {
// to invoke another constructor from same class, this() constructor is used
this();
System.out.println("Employee class >> "
+ "Inside parametrized constructor with 2 arguments (String, int)");
// initialize
this.employeeName = name;
this.employeeId = id;
}
// 4. display() method
void displayEmployeeInfo() {
System.out.println("\nEmployee details: \n\nOrgnaization: " + employeeOrg
+ "\nId: " + employeeId
+ "\nName: " + employeeName + "\n");
}
// 5. main() method
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 2 arguments (String, int)
Employee details:
Orgnaization: Google Corporation Inc.
Id: 19
Name: Rahul Dravid
Related Articles:
- Java Constructor with example
- Default constructor
- Parametrized constructor
- Constructor overloading
- Constructor chaining
- Constructor v/s Methods
References:
Happy Coding !!
Happy Learning !!