If a class A makes public Object's clone()
method:
@Override
public Object clone() {
return super.clone();
}
What will be the instanceof
(or getClass()
) of an instance of A created using clone()
?
What about instances of class B extends A
created using the clone()
method ?
EDIT
Clarification: I ask this because even before compiling, Eclipse java editor requires to cast the returned clone() instance to the assigned object. Which suggest that the returned class is Object
(which technically it is, but all the answers so far say the class should be A)
A original = new A();
A cloned1 = original.clone(); // Eclipse marks this as error
A cloned2 = (A) original.clone(); // This is OK
It will be the same type as the original object as long as it uses Object.clone()
by calling super.clone()
and that should be done by convention.
Read the doc here.
This prints String
but it is wrong by convention:
public class SomeTest {
@Override
protected Object clone() {
return "";
}
public static void main(String[] args) {
System.out.println(new SomeTest().clone().getClass().getSimpleName());
}
}
The same as the initiator by means the original parent class whic always uses Object.clone() by calling the super.clone(). For more visit
http://howtodoinjava.com/2012/11/08/a-guide-to-object-cloning-in-java/
https://www.artima.com/objectsandjava/webuscript/ClonCollInner1.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With