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

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 private and final like a name?

Using the setter requires more lines of code:

Person p1 = new Person();
p1.setName("Alex");

using the constructor requires only one line

Person p1 = new Person("Alex");

Now for the point about final fields, you likely aren't ever going to change the name of that Person object 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 the Person objects name in the future

public class Person {
    
    private final String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

}

The above Person object guarantees that whatever the initial name is 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

2

u/[deleted] Sep 19 '22

[removed] — view removed comment

6

u/dionthorn this.isAPro=false; this.helping=true; Sep 19 '22 edited Sep 19 '22

Even then you could just have a

marriage(Person)

and then internally change the name state.

public class Person {

    private final String firstName;
    private String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getName() {
        return this.firstName + " " + this.lastName;
    }

    public String getFirstName() { return this.firstName; }

    public String getLastName() { return this.lastName; }

    public void marriage(Person toMarry) {
        this.lastName = toMarry.getLastName();
    }
}

No need to expose internal state with setters if you don't have to.

if Frank marries Beth

Person frank = new Person("Frank", "Smith");
Person beth = new Person("Beth", "Sue");
beth.marriage(frank); // now beth lastName is Smith