Can anyone explain why I need to create a constructor at all when I can just make an regular object and do the same things? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can anyone explain why I need to create a constructor at all when I can just make an regular object and do the same things?

4th Feb 2016, 2:11 PM
Syed Ruman
2 Answers
+ 2
a constructor is always needed if you want to create a object. It becomes important if you create objects that needs specific fields E.g. a person usually has a name. then you can write a constructor that looks like this : public Person (String name){ this,name=name; } to ensure that every person gets a name on creation.
23rd Mar 2017, 12:19 PM
T0nd3
+ 1
Sometimes you will need to pass parameters to initialize some of the object fields on creating. You may use the default constructor which accepts no parameters and you don't even need to write it in your class code. Java puts it there hidden for you.
29th Apr 2016, 9:59 AM
Anton Cholakov
Anton Cholakov - avatar