Yes, because the clone() method is protected it can be only inherited, but you can't call it on object of another class.
Every class inherit Object, so you can just call clone().
But in (default/native) clone() method you have an if(){} in which if your class not implements Cloneable, it will throw an Exception CloneNotSupportedException.
I said native because, the clone() method is native, when you call it, in back is
called another method writed in C++.
Here is a small part of the code which is called when you call clone().
if (!klass->is_cloneable()) {
ResourceMark rm(THREAD);
THROW_MSG_0(vmSymbols::java_lang_CloneNotSupportedException(), klass->external_name());
}
thanks Is it possible to find the source for a Java native method?
you can use reflection to call the clone method without override it in your object.
public class Main{
public static void main(String[] args) throws CloneNotSupportedException {
A a = new A();
Object o = new Object();
Method method = null;
try {
method = o.getClass().getDeclaredMethod("clone");
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
method.setAccessible(true);
try {
System.out.println(method.invoke(a));
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
class A implements Cloneable {
}
and method.invoke(a) instanceof A
is evaluated as true
without implementing Cloneable you will get
Caused by: java.lang.CloneNotSupportedException: defaultPackage.A
at java.lang.Object.clone(Native Method)
And because Integer don't implements Cloneable, the clone() method will throw java.lang.CloneNotSupportedException.