I am a newbie in java and was wondering "Why default constructor is not provided by compiler when class contains parametrized constructor defined by user?"
Asked
Active
Viewed 297 times
-1
-
2Why do you think it should? – Nicholas K May 03 '19 at 08:30
-
5Because that is how it is. And because ALWAYS having a default constructor is VERY bad practice because what values are all your fields supposed to have? `null`? – luk2302 May 03 '19 at 08:30
-
5default constructors are only a convenience. You are better off giving fields a reasonable initial value if you can. – Peter Lawrey May 03 '19 at 08:31
-
Next to the explanation which are already given. Maybe you're interested in lombok. Which can help to do some simplification writing POJOs and other classes with annotations. https://projectlombok.org – Manuel May 03 '19 at 08:37
1 Answers
5
When an author decides to not provide any constructor, it is perfectly fine that the compiler adds that default constructor. Obviously the user doesn't care "how" objects of that class are created, he accepts that the "default" kicks in.
But as soon as the author writes down a constructor with parameters, it is also obvious that he assumes that one of his constructors gets used.
The straight forward reasoning: assume your class has multiple fields, and the user-written constructor initializes all of them. What should the compiler-generated default constructor do about these fields?! And as one of the comments pointed out: leaving them at null
or maybe 0 isn't a good idea.

GhostCat
- 137,827
- 25
- 176
- 248