java - Downcasting while calling super.clone() method -
consider following program
class implements cloneable { string str = null; public void set(string str) { this.str = str; } @override public clone() { a = null; try { = (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 = new a(); a.set("1234"); b = a.clone(); } }
why output of above program 1234 , not null.
i expecting null, because of following understanding of mine.
super.clone() method create new object of parent type (object in case) in attributes of parent class shallow copied.
when downcasting in our clone() method, attributes defined in child class initialised default values, since new object.
but after looking @ output, seems attribute values of current instance of child class (this) getting copied newly contructed object (after calling clone of parent class , downcasting).
can please tell going on when downcasting?
1234 correct result... let's see why:
create new a
instance:
a = new a();
set value a.str
a.set("1234");
clone a
a b = a.clone();
first of all, note, we're using clone()
method instance a
, let's go there:
@override public clone() { // create new instance, not set null!!! // reference caller (a.clone in main) // must use keyword i.e: this.str = null a = null; try { // call cloneable::clone() method = (a) super.clone(); // filled data of instance print 1234 if(a.str!=null) { system.out.println(a.str); } // unused code in case else { system.out.println("null"); } } catch (clonenotsupportedexception e) { e.printstacktrace(); } // return cloned instance return a; }
Comments
Post a Comment