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
14
u/dionthorn this.isAPro=false; this.helping=true; Sep 19 '22 edited Sep 19 '22
why would you use a setter for a private field, which you might not want to expose to a setter in the first place if it's truly something
privateandfinallike aname?Using the setter requires more lines of code:
using the constructor requires only one line
Now for the point about
finalfields, you likely aren't ever going to change thenameof thatPersonobject it will always be"Alex"By not exposing the field to a setter you guarantee the
somePerson.getName()will always return the same and people can't muck up thePersonobjectsnamein the futureThe above
Personobject guarantees that whatever the initialnameis it will always be that initial value.If you expose a setter than you have no such guarantee.
The Oracle docs have a section on OOP concepts:
https://docs.oracle.com/javase/tutorial/java/concepts/object.html
as well as access control:
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html