What is a copy constructor?
Can someone share a small example that can be helpful to understand along with defensive copying p
Copy constructors one often sees in C++ where they are needed for partly hidden, automatically invoked operations.
java java.awt.Point
and Rectangle
come to mind; also very old, mutable objects.
By using immutable objects, like String
, or BigDecimal
, simply assigning the object reference will do. In fact, due to the early phase of Java after C++, there still is a
silly copy constructor in String:
public class Recipe {
List ingredients;
public Recipe() {
ingredients = new ArrayList();
}
/** Copy constructor */
public Recipe(Recipe other) {
// Not sharing: ingredients = other.ingredients;
ingredients = new ArrayList();
ingredients.addAll(other.ingredients);
}
public List getIngredients() {
// Defensive copy, so others cannot change this instance.
return new ArrayList(ingredients);
// Often could do:
// return Collections.immutableList(ingredients);
}
}