class Main {
public static void main(String[] args) {
new Cloned().clone();
}
}
class Cloned implements Cloneable {
}
This gives an error, saying it is protected. None of the subclasses of object can call that method.
clone is protected because it is something that ought to be overridden so that it is specific to the current class. While it would be possible to create a public clone method that would clone any object at all this would not be as good as a method written specifically for the class that needs it.
clone() is protected soo outside to java. lang package we can access this method in subclass directly or with subclass Object only. clone must not be called on non-cloneable objects, therefore it is not made public.
That's the reason to have protected methods in Object -- so that classes can use the method internally, but outside code cannot invoke that method on it. And the Cloneable interface has nothing at all to do with the fact Object. clone() is protected.
clone method produces an instance of whatever class it is called on; this cannot be reproduced without native code. This is why the Object. clone method could not have been avoided. Cloneable could have contained a clone method, but it would create issues regarding the throws clause.
because clone()
is protected method in the class Object
if you want clone()
to be accessed publically, u need to override that method in ur class.
@override
public Object clone()
{
return super.clone();
}
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