Search code examples
javaclone

Object cloning error


have a doubt please clarify me Let me explain Having 2 classes class A and B

public class A implements Cloneable{

    public static void main(String[] args) {

        A a1 = new A();
        try {
            A a2 = (A) a1.clone();//works fine
        } catch (CloneNotSupportedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        B b1 = new B();
        B b2 = (B) b1.clone();//cannot get this method

    }

}

class B implements Cloneable {

}

when i compiled this code got following error

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
The method clone() from the type Object is not visible

I know both classes extends Java.lang.Object Class please explain why class B cannot get clone() method


Solution

  • The clone() method is protected. As your main is part of the class A it allowed to call protected methods on objects of type A and thus the a.clone() will just work fine.

    The b.clone() fails as clone is protected and thus not available outside of the B class, unless it would be publicly overridden by B.

    Here is the Javadoc about the clone method.