Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is instanceof of a cloned object?

Tags:

java

clone

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 
like image 619
ilomambo Avatar asked Feb 21 '14 09:02

ilomambo


2 Answers

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());
    }
}
like image 135
aalku Avatar answered Oct 16 '22 03:10

aalku


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

like image 22
Jitesh Upadhyay Avatar answered Oct 16 '22 02:10

Jitesh Upadhyay