A constructor is basically a method that you can use to ensure that objects of your class are born valid. This is the main motivation for a constructor.
Let's say you want your class has a single integer field that should be always larger than zero. How do you do that in a way that is reliable?
public class C {
private int number;
public C(int number) {
setNumber(number);
}
public void setNumber(int number) {
if (number < 1) {
throws IllegalArgumentException("C cannot store anything smaller than 1");
}
this.number = number;
}
}
In the code above, it may look like you are doing something redundant, but in fact you are ensuring that the number is always valid no matter what.
"initialize the instances of a class" is what a constructor does, but not the reason why we have constructors. The question is about the purpose of a constructor. You can also initialize instances of a class externally, using c.setNumber(10)
in the example above. So a constructor is not the only way to initialize instances.
The constructor does that but in a way that is safe. In other words, a class alone solves the whole problem of ensuring their objects are always in valid states. Not using a constructor will leave such validation to the outside world, which is bad design.
Here is another example:
public class Interval {
private long start;
private long end;
public Interval(long start, long end) {
changeInterval(start, end);
}
public void changeInterval(long start, long end) {
if (start >= end) {
throw new IllegalArgumentException("Invalid interval.");
}
this.start = start;
this.end = end;
}
public long duration() {
return end - start;
}
}
The Interval class represents a time interval. Time is stored using long. It does not make any sense to have an interval that ends before it starts. By using a constructor like the one above it is impossible to have an instance of Interval at any given moment anywhere in the system that stores an interval that does not make sense.