0

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;
    }
}

1 Answer 1

1

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 !

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer. I actually understand the relationship expressed by inheritance and composition. I just got confused by "nested objects". Where the heck are the nested objects in this case??? And the copy() method actually works. I just wanna make sure that's what the question asks for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.