Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If all class extends object why can't they all call clone

Tags:

java

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.

like image 698
rubixibuc Avatar asked Jul 29 '12 06:07

rubixibuc


People also ask

Why is clone () protected?

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.

Can we directly call clone () method on the object of some class?

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.

Why is object clone () method available only to classes that implement cloneable interface?

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.

Why clone method is not in cloneable interface?

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.


1 Answers

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();
}
like image 193
PC. Avatar answered Nov 14 '22 22:11

PC.