What is the need for using Constructor?Can'twe just initialize a data member in a method? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

What is the need for using Constructor?Can'twe just initialize a data member in a method?

Does Constructors have any special significance?Pls explain in simple language.?(IN JAVA)

10th Nov 2018, 5:42 PM
Neelarghya Kundu
Neelarghya Kundu - avatar
2 Answers
+ 6
Constructor just serves to makes operations (like setting a atributte) or call a method when a object is created . It's not obrigatory to use it but for readability you can leaves empty. But normally you can always set your attributes (if you have some value to set) with a standart value. It's a good practice.
10th Nov 2018, 6:02 PM
Anya
Anya - avatar
+ 3
Wouldn't that make things unnecessarily difficult? You would need to instanciate the 'empty' object, then 'fill it up' afterwards. With a constructor you can initialize the object in a single line.
10th Nov 2018, 6:01 PM
HonFu
HonFu - avatar