Child not seeing clone () due to access violation?

When I implement Cloneable

in a class, say a class AA

, the class AA

is cloned - I can call clone()

on its object without getting it CloneNotSupportedException

. I can do this
without overriding clone()

(although it is recommended that the object not depend on its clone).

When a class Cloneable

, that is, its descendants.

In the following code

class ZZ {protected void mm(){System.out.println("+++");}}

class AA extends ZZ implements Cloneable {    
    // ...
    protected Object clone () throws CloneNotSupportedException {return super.clone();}
    AA cloneMe() throws CloneNotSupportedException { return (AA)clone(); }
}

class C extends AA  {
    public static void main(String[] args) throws CloneNotSupportedException {
        C c = new C();        
        AA a = new AA(); 
        AA a22 = (AA)(c.clone());   
        AA a3 = a.cloneMe();   
        C c2 = (C)c.clone();  

        AA a21 = (AA)a.clone();   
        a.mm();
    }
}

      

I am getting logged error which is

clone() has protected access in Object

      

in line

    AA a21 = (AA)a.clone();   

      

when i comment out the implementation clone()

in AA

, i.e. the line

   // protected Object clone () throws CloneNotSupportedException {return super.clone();}

      

Since it AA

is cloned, I should be able to clone its instance without implementing it clone()

in AA

. AA

inherits clone()

from Object

.

So - how does this error come about ???

TIA.

// =======================================

EDIT:

I have the same problem with the code above, except for the class ZZ

, which is the following code:

class AA implements Cloneable {    
    // ...
    // protected Object clone () throws CloneNotSupportedException {return super.clone();}
    AA cloneMe() throws CloneNotSupportedException { return (AA)clone(); }
}

class C extends AA  {
    public static void main(String[] args) throws CloneNotSupportedException {
        C c = new C();        
        AA a = new AA(); 
        AA a22 = (AA)(c.clone());   
        AA a3 = a.cloneMe();   
        C c2 = (C)c.clone();  

        AA a21 = (AA)a.clone();   

    }
}

      

class ZZ

was there to show that calling a method by protected

"grandson" does not give the same error as when called in a clone()

similar way.

// ============================================= ==

EDIT-2:

The answer in super.clone () does not work in Derived Class says

"Clone is one of the early designs in java and it has flaws".

      

this seems to be the only explanation. looking to further test this.

I've looked over this before and without success - more on native methods than explaining them in the Java docs. However, there is any for internal elements clone()

- how is it implemented, how does it clone members, etc., and also how does it "manage" this unusual access privilege? and in the circumstances

+3


source to share





All Articles