I found a solution to this that works with both inheritance and aggregation - Here is a simple object structure:
//This is our SuperClass
public class Human {
private String hairColor; //Instance variable
public Human (String color) { // Constructor
hairColor = color;
}
public String getHairColor () { //Accessor method
return hairColor;
}
}
//This is our beard object that our 'Man' class will use
public class Beard {
private String beardColor; // Instance variable
public Beard (String color) { // Constructor
beardColor = color;
}
public String getBeardColor () { // Accessor method
return beardColor;
}
}
// This is our Man class that inherits the Human class attributes
// This is where our deep copy occurs so pay attention here!
public class Man extends Human {
// Our only instance variable here is an Object of type Beard
private Beard beard;
// Main constructor with arg
public Man (Beard aBeard, String hairColor) {
super(hairColor);
beard = aBeard;
}
// Here is the COPY CONSTRUCTOR - This is what you use to deep copy
public Man (Man man) {
this(new Beard(man.getBeard().getBeardColor()), man.getHairColor());
}
// We need this to retrieve the object Beard from this Man object
public Beard getBeard () {
return beard;
}
}
Sorry this example wasn't very unisexy.. it was funny to me at first.
The Beard object was thrown in just to show a more difficult example that I struggled with when I was working with inheritance and deep copy. That way when you're using aggregation you'll know what to do. If you don't need to access any objects and just primitives it's a little bit more simple, you can just use the class instance variables.
public class Man extends Human {
private String moustache;
private double bicepDiameter;
public Man (String aMoustache, double bicepSize) {
this.moustache = aMoustache;
this.bicepDiameter = bicepSize;
}
// This is the simple (no-object) deep copy block
public Man (Man man) {
this(man.moustache, man.bicepDiameter);
}
}
I really hope this helps! Happy coding :)