Java default constructor

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

Create another class named Employee.java

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.

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.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *