Why Java doesn't provide default constructor, if class has parametrized constructor? Consider the following example
class A {
int a;
public A() {
}
public A(int val) {
a = val;
}
}
Here I explicitly need to add default constructor. Is there any reason, why Java doesn't provide default constructor for class having parametrized constructor?
Java provides a default no-argument constructor only for those classes which don't have a constructor explicitly defined for them. Once a constructor is defined by the programmer (even if it is a no-argument constructor), the default constructor is not provided.
If there is any one parametrized Constructor present in a class, Default Constructor will not be added at Compile time. So if your program has any constructor containing parameters and no default constructor is specified then you will not be able to create object of that class using Default constructor.
We can have any number of Parameterized Constructor in our class. In this example, I have implemented four constructors: one is default constructor and other three are parameterized. During object creation the parameters we pass, determine which constructor should get invoked for object initialization.
The compiler automatically provides a no-argument, default constructor for any class without constructors.
The reason has to do with a combination of security and interface. The compiler shouldn't give you methods you don't explicitly define. The one exception is a convenience no-arg constructor if you don't specify any constructors. If you do specify a constructor the compiler assumes you don't want any others.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With