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