In this post, we will see about Java default constructor.
Default constructor
is the no arg constructor which is inserted by compiler unless you provide any other constructor explicitly.
You won’t able to see it as it is present in class file rather than source file.
Is there any difference between no argument constructor and default constructor?
If you provide any constructor in class, it’s no longer default constructor.There is lots of debate on it but it is my opinion.
When you do not provide any constructor, compile will insert default constructor which will call super class’s default constructor.You need to make sure that super class has no-arg constructor.
Let’s understand this with the help of an example
Create a class named Person.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package org.arpit.java2blog.constructor; public class Person { String name; int age; public Person(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } |
Create another class named Employee.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package org.arpit.java2blog.constructor; public class Employee extends Person { int empId; public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } } |
You will get compilation error at line with this message.
"Implicit super constructor Person()
is undefined for default constructor. Must define an explicit constructor"
As you can see here, it tells you that Person class should have explicit constructor else it won’t compile.
Once you add no arg constructor to Person
class, you won’t get compilation error anymore.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package org.arpit.java2blog.constructor; public class Person { String name; int age; // Added explicit constructor public Person() { System.out.println("Added explicit constructor"); } public Person(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } |
As you can see once you add explicit constructor to Person class, there won’t be any compilation error in Employee class.
That’s all about default constructor in java.