r/javahelp • u/[deleted] • Sep 19 '22
Constructor vs initialising manually
Sometimes I’m confused why we need constructor if we can initialise objects manually:
Example:
Person p1 = new Person(); //so we have default constructor
p1.name = “Alex”;or if name is private just we can use get method
Why we actually need a constructor? I read a comment somewhere and they told like it’s wrong to initialise fields manually so always use a constructor, but why?
Like we use constructor to initialise fields of objects or it has some more functionalities?
I’m confused.
17
Upvotes
4
u/loomynartylenny half-decent at Java Sep 19 '22
So you can set initialize the object's fields all at once instead of having to set each and every one manually whenever you create a new instance of the object.
After all, suppose that
Personhad a constructor that took aStringas an argument to set thenamefield, such as:With this constructor, you could then do the same thing as your example with just
Much simpler than creating a person but then only setting the name of that person after constructing it