Do I really need to define default constructor in java?
A no-arg constructor is automatically inserted for you, if you don't write one. This means, if you write a constructor with some parameters, it will be the only constructor you have, so you must pass some values for those parameters to create an instance of it.
A default (no-argument) constructor is automatically created only when you do not define any constructor yourself.
If you need two constructors, one with arguments and one without, you need to manually define both.
While all the answers above are correct, it's a bit difficult for new-comers to wrap it in their head. I will try to answer the question anew for new-comers.
The problem that Ayush was facing was in trying to instantiate an Object
for a class via a no-arg constructor. This class however has one or more parameterized constructor and this results in a compile time error.
For example, let us create a class Student
with a single parameterized constructor and try to instantiate it via the no-arg constructor.
public class Student {
private String name;
private int rollNo;
public Student(String name, int rollNo) {
this.name = name;
this.rollNo = rollNo;
}
public static void main(String[] args) {
// The line below will cause a compile error.
Student s = new Student();
// Error will be "The constuctor Student() is undefined"
}
}
Woha! But when we remove the public Student(String name, int rollNo)
constructor all-together, the error is gone and the code compiles.
The reason behind this seeming anomaly lies in the fact that Java only provides us with the default (no-arg) constructor when we do not define any constructor for that class on our own.
For example, the following class is supplied with a default contructor:
public class Student {
private String name;
private int rollNo;
}
becomes:
public class Student {
private String name;
private int rollNo;
//Default constructor added by Java.
public Student() {
super();
}
}
In other words, the moment we define any parameterized constructor, we must also define a no-arg constructor if we want to instantiate the object of that class via a no-arg constructor.
Also in case of inheritance, a sub-class with no constructors; is supplied one default constructor. This default constructor supplied by Java as above calls the super class's no-arg constructor. If it can't find one, then it will throw an error.
So yes it's always a good choice to define a no-arg/default constructor.
Ref : Oracle Java Tutorial