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

•

u/AutoModerator Sep 19 '22

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions

  • You include any and all error messages in full

  • You ask clear questions

  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

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

5

u/[deleted] Sep 19 '22

Good example, now I got the idea.

3

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

This particular concept in java OOP is known as Encapsulation and is one of the 4 primary OOP concepts in java, here is a more complicated breakdown of the concept:

https://stackify.com/oop-concept-for-beginners-what-is-encapsulation/

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

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..

12

u/tsvk Sep 19 '22

It also prevents creation of objects with internal states that are not allowed or inconsistent. If every person needs a name and it is not allowed/coherent/meaningful to have persons without names, then the name should be a constructor parameter so that the name field is initialized at object creation. Otherwise, the object is in an invalid state in between calling the no-args constructor and setting the name manually separately.

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)

11

u/skidwiz Extreme Brewer Sep 19 '22 edited Sep 19 '22

There are a lot of good answers here, but I'm going to go ahead and throw my hat into the ring.

Your question is very complex (probably much more so than you intended). A class can be constructed any number of ways. I'll try to go over a few of them before I answer your question.

Default Constructor

Every Java class contains an empty constructor by default. This empty constructor is basically an invisible No-Arg Constructor. It doesn't care about the fields. It just tells Java that the class exists. Java creates this at compile time automatically if it doesn't detect one.

No-Arg Constructor

A No-Arg Constructor instantiates the class without instantiating the fields within the class. Consider a String. When you instantiate a String, such as String myString = new String(), You aren't actually making anything. If you try to print this, you won't get an error. In fact, you won't get anything. The variable myString isn't null. If you were to run System.out.println(Objects.isNull(myString)), you will get false. So, it exists, and it is insantiated, but it is empty. In fact, running System.out.println(myString.isEmpty()) will return true. So, the String exists, and will avoid an NPE if called, but it doesn't do anything.

However, a No-Arg Constructor doesn't have to do nothing. What I described above is literally the exact same as if you just used the Default Constructor. But, what if I want a default value. What if, for example, I want String to always say "I'm a String" when I instantiate it using the No-Arg Constructor? I can simply update the constructor to create that value.

public String(){
  this.value = "I'm a String";
}

Note: The above code is an example. Don't try it.

Now, this will always create a String with that value if it is instantiated using the No-Arg Constructor. This is a good way to create a default value. Another way is to instantiate that value when the field is create at the class level, i.e. private String value = "I'm a String";. Whether you want to make that field private, static, final, synchronized, or whatever is up to you.

Parameterized Constructor

A parameterized constructor takes the argument to create the value. String myString = new String("I'm a String"); works to create the String object with the value you want. It can be overloaded.

Other ways to create objects

I'm including these here for completeness.

  • Builder: The builder is used when an object has a large number of parameters and overloading would be confusing or overly verbose.

  • Static factory method: Static factory methods are an important part of the programmers toolkit. It returns an instance of the class directly without the need to instantiate it. Joshua Bloch makes this his number 1 best Java practice in his book Effective Java for a reason.

  • Private Constructor: This is used in static classes to ensure non-instantiability. It can be used in utility classes, singleton classes, etc. It basically just makes sure that the Default Constructor isn't created by the JVM.

I'm not going to go into detail about these objects, but feel free to look them up if you are interested in them.

So, why do we need a Constructor?

Now that we see the myriad of ways to create an object, we see that some things are left to style, and some things are left to best practices. However, the main reason we use constructors is safety, and the secondary reason is flexibility. Similar to how we use scope declarations to limit the visibility of our objects and values, we use constructors to hide some of our implementation details. This is similar to the same reason we use interfaces whenever possible. While a simple constructor doesn't explain this very well, consider a constructor for a more complex object that may need logic implemented at the time it is created.

Consider an Object called Distance. Obviously Java has no datatype for Kilometers or miles, so we have to store any number within distance as a double. But, do we want to store it as a kilometer or a mile? If we decide we want to do only Kilometers, but allow for the object to be constructed using miles, then we should allow for a constructor to change this:

public Distance(Double distance, DistanceTypes type){
  if (DistanceTypes.KILOMETERS == type){
    this.distance = distance;
  } else {
    this.distance = convertType(distance, type);
  }
}

Likewise, what if this method is called through an API via an Interface, and the interface only has one constructor. How to we construct the object in different ways? For example, what if the above constructor is the only one available via the interface, but I want to just pass a distance. I can create a constructor in Distance that calls the other constructor. This is called constructor chaining.

Finally in addition to all these reasons, it makes for cleaner code. return new Distance(25, DistanceTypes.MILES); is much cleaner and easier to read then:

Distance distance = new Distance();
distance.setDistance(25);
distance.setType(DistanceTypes.MILES);
return distance;