Why default constructor is not provided by compiler when class contains parametrized constructor defined by user? [duplicate]

只谈情不闲聊 提交于 2019-12-20 07:47:46

问题


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?"


回答1:


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.



来源:https://stackoverflow.com/questions/55965999/why-default-constructor-is-not-provided-by-compiler-when-class-contains-parametr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!