Consider the following program
class A implements Cloneable {
String str = null;
public void set(String str)
{
this.str = str;
}
@Override
public A clone()
{
A a = null;
try {
a = (A) super.clone();
if(a.str!=null) {
System.out.println(a.str);
}
else {
System.out.println("null");
}
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return a;
}
public static void main (String args[])
{
A a = new A();
a.set("1234");
A b = a.clone();
}
}
Why output of above program is 1234 and not null.
I was expecting null, because of following understanding of mine.
super.clone() method will create a new object of parent type (Object in this case) in which attributes of parent class will be shallow copied.
When we do downcasting in our clone() method, then attributes defined in child class will get initialised with their default values, since this is a new object.
But after looking at the output, it seems like attribute values of current instance of child class (this) are getting copied to newly contructed object (after calling clone of parent class and downcasting).
Can someone please tell what is going on when we are downcasting?