What kinds of constructor does Java support, and how do the default, parameterised and copy kinds differ in what they guarantee?
Java supports three kinds of constructor. The default one, the parameterised one and the copy one, and they differ in what they promise about the object that comes out.
public class Main {
public static void main(String[] args) {
Product plain = new Product();
Product priced = new Product("Notebook", 4.5);
Product copy = new Product(priced);
System.out.println(plain.name()); // empty
System.out.println(priced.name()); // Notebook
System.out.println(copy.name()); // Notebook
}
}
And here is the class.
public class Product {
private String name;
private double price;
public Product() {
this("Unnamed", 0.0);
}
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public Product(Product other) {
this.name = other.name;
this.price = other.price;
}
public String name() {
return name;
}
}
So what does each one guarantee?
the kind what it guarantees
-------------------- ------------------------------------------------
the default the object exists and every field has a
sensible value, even if that value is empty
the parameterised the object has exactly the values you gave
the copy the object starts with the same values as
the one you copied
And the first kind is the one that surprises people. Java only gives you a default constructor when you have not written any constructor at all. As soon as you write one, the free one is gone. So in the code above the Product() constructor has to be written by hand.
// This class has a free default constructor.
public class Simple {
private String name;
}
// This class does not, because a constructor was written.
public class WithOne {
private String name;
public WithOne(String name) {
this.name = name;
}
}
And there is one detail worth knowing about the copy constructor. It takes an object of the same type and copies the values across one by one. And it makes a real copy, so changing the copy does not change the original. That is different from just assigning the reference, which would give you two names for the same object.
And there is a catch with the copy constructor and with the default constructor, and it comes up with inheritance. When a class extends another, the child constructor always calls some parent constructor, either one that you write or the default one. If the parent has no default constructor then the child must write a super call, or the code does not compile.
So the rule to remember is this. The default gives you a safe empty object, the parameterised gives you exactly what you asked for, and the copy gives you a separate object with the same values.
The last question in this topic names the kinds and says when each is used.