r/javahelp • • 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

11 comments sorted by

View all comments

4

u/loomynartylenny half-decent at Java Sep 19 '22

I read a comment somewhere and they told like it’s wrong to initialise fields manually so always use a constructor, but why?

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 Person had a constructor that took a String as an argument to set the name field, such as:

public Person(String myName){
  name = myName;
}

With this constructor, you could then do the same thing as your example with just

Person p1 = new Person("Alex"); // we create a person called Alex

Much simpler than creating a person but then only setting the name of that person after constructing it

0

u/[deleted] Sep 19 '22

So it’s just simpler..

5

u/loomynartylenny half-decent at Java Sep 19 '22 edited Sep 19 '22

And will save you a lot of time and energy later on

(and that's before we start factoring in things such as the internal state of instances, final instance fields, fields that only have a getter but no setter, anonymous objects, and other such design considerations that can render it impossible/inadvisable to set every single field of an object manually)