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

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;