简体   繁体   中英

General java override clone method

Lets say I have super class A with clone able interface and deep overridden clone method.

I also have a subclass B.

B Temp = new B();
B Temp_Clone = (B) Temp.clone();

The method Temp.clone() returns a reference to the cloned super class A, right?

From my understanding, I can't put a reference to a super class in a sub class object, right?

So how is the code I written here is possible? because of the casting?

Thanks.

The class Object's clone() method creates and returns a copy of the object, with the same class and with all the fields having the same values. However, Object.clone() throws a CloneNotSupportedException unless the object is an instance of a class that implements the marker interface Cloneable.

The method Temp.clone() returns a reference to the cloned super class A, right?

Right.

From my understanding, I can't put a reference to a super class in a sub class object, right?

Wrong.

So how is the code I written here is possible? because of the casting?

I don't know what you think is impossible about it, but the casting is certainly required.

Well, if the code in A called super.clone so the object that created when you call Temp.clone is object from the type B. since clone does not call constructor! clone method implemented in the object class as native class and preform member wise copy and create the same object as the this object. so ClonedTemp is from B type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM