Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is mandatory to have a default constructor along with parameterized constructor in Java?

Many a time I have got an exception saying "the default constructor's implementation is missing". And many a times a parameterized constructor's definition alone does everything. I want to know under which conditions this happens.

like image 959
Nihal Sharma Avatar asked Dec 04 '22 14:12

Nihal Sharma


2 Answers

The compiler doesn't ever enforce the existence of a default constructor. You can have any kind of constructor as you wish.

For some libraries or frameworks it might be necessary for a class to have a default constructor, but that is not enforced by the compiler.

The problem you might be seeing is if you have a class with a custom constructor and you don't have an implicit super() call in your constructor body. In that case the compiler will introduce a call to the super classes default constructor. If the super class doesn't have a default constructor then your class will fail to compile.

public class MyClass extends ClassWithNoDefaultConstructor
    public MyClass() {
        super(); //this call will be added by the compiler if you don't have any super call here
        // if the super class has no default constructor the above line will not compile
        // and removing it won't help either because the compiler will add that call
    }
}
like image 142
Joachim Sauer Avatar answered Dec 07 '22 02:12

Joachim Sauer


If there is no Constructor present in a class, one Default Constructor is added at Compile time.

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.

Eg:

class A{

A(int a){}

}

A a = new A() -----> Error.

-------------------------------------------------------

class A{

A(int a){}

A(){}

}

A a = new A() -----> It will work.

-----------------------------------------------------------

class A{

}

A a = new A() -----> It will work.
like image 40
Jayesh Avatar answered Dec 07 '22 02:12

Jayesh