Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Java doesn't provide default constructor, if class has parametrized constructor? [duplicate]

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?

like image 641
rigel Avatar asked Apr 16 '13 20:04

rigel


People also ask

Will Java supply the default constructor if the class already contains a parameterized 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.

Can we have parameterized constructor without default constructor in Java?

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.

Can we have both default constructor and parameterized constructor in the same class?

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.

Does every class in Java automatically have a default constructor?

The compiler automatically provides a no-argument, default constructor for any class without constructors.


1 Answers

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.

like image 200
Chris Gerken Avatar answered Oct 02 '22 00:10

Chris Gerken