Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I really need to define default constructor in java?

It works fine when constructors are not defined, but gives errors if I define a parameterized constructor and not a default one and not passing any values while creating an object. I thought constructors are predefined.

Why do I need to define a default constructor if I've defined a parameterized constructor? Ain't default constructor predefined?

like image 934
Ayush Goyal Avatar asked Sep 04 '10 06:09

Ayush Goyal


People also ask

Is it necessary to declare default constructor in Java?

Java doesn't require a constructor when we create a class. However, it's important to know what happens under the hood when no constructors are explicitly defined. The compiler automatically provides a public no-argument constructor for any class without constructors. This is called the default constructor.

Does Java automatically create a default constructor?

Java Default Constructor If we do not create any constructor, the Java compiler automatically create a no-arg constructor during the execution of the program. This constructor is called default constructor.

Do all classes need a default constructor?

You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass.


1 Answers

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.

like image 56
Justin Ardini Avatar answered Oct 05 '22 01:10

Justin Ardini