Search code examples
javainheritancecopydeep-copy

Copy nested objects in Java


So I have the following classes:

class A{
    public A(int n1){
        n=n1;
    }
    int n;
}

class B extends A{
    public B(int n2){
        super(n2);
        cnt=1;
    }
    int cnt;
}
class C extends B{
    public C(int n3){
        super(n3);
        clr="red";
    }
    String clr;
}

public class Driver {
    public static void main(String[] args){
        A a,b,c,d,e;
        a=new B(200); d=a.copy();
        b=new C(100); e=b.copy();
    }
}

I am asked to define the method copy() in classes A,B,C. The copy method essentially makes a copy of all nested objects.

I have 2 questions:

  1. I don't see any nested objects being constructed, why does he ask me to make a copy of all nested objects? Is it because when I construct a subclass object, a base class object is constructed and nests inside the subclass object?

  2. Is it correct to write the method as follows (take class B for example):

class B extends A{
    public B(int n2){
        super(n2);
        cnt=1;
    }
    int cnt;
    public A copy(){
        A copy_ref=new B(1);
        ((B)copy_ref).cnt=this.cnt;
        copy_ref.n=super.n;
        return copy_ref;
    }
}

Solution

  • I think you are confusing to different concepts.

    You are confusing the has-a relationship with the is-a relationship.

    In your code C is a B and also an A: C has an is-a relationship with B and A.
    C does not contain an instance of B or A (that would be an has-a relationship).

    Since C is an B and A, it contains all the members of B and A. Calling a copy of C will copy all of its members variables. You do not need to create any particular method, you can just use the already defined Object.clone method.

    If you want to define your own clone/copy method I suggest you look at the following article on the subject.

    Enjoy !