views:

39

answers:

2

If I do an override of a clone method the compiler create a bridge method to guarantee a correct polymorphism (THIS IS THE CLASS DECOMPILED)

class Point
{

    Point()
    {
    }

    protected Point clone()
        throws CloneNotSupportedException
    {
        return this; // not good only for example!!!
    }

    protected volatile Object clone()
        throws CloneNotSupportedException
    {
        return clone();
    }
}

so when is invoked the clone method the bridge method is invoked and inside it is invoked the correct clone method. But my question is when into the bridge method is called return clone() how do the VM to say that it must invoke Point clone() and not itself again???

A: 

This code doesn't compile with java 1.6. Method signatures in Java don't include the return type... and you can't have duplicate method signatures.

Tim Bender
yes, sorry I referred to the Java decompiled code...
xdevel2000
+1  A: 

You cannot do that, it won't compile because you have two methods with the same name and same parameters (none in this case) and if you call somePoint.clone() it's not clear which one is meant.

You're supposed to do something like:

public Point clone() {
    return (Point) super.clone(); // shallow copy
}

Edit: some finer points: Your class is supposed to implement the cloneable interface otherwise super.clone() will give the exception. The clone() method in the Object class returns a shallow copy of the current object (it's runtime class will be the same as the one of the object that the clone method was called on). It's your job then to do any class specific manipulation on that object (like cloning references to other objects) and then return it. The return type can be your own class instead of Object, and it will still overwrite Object.clone() (or any other ParentClass.clone()) method.

Andrei Fierbinteanu
sorry read again if you want... thanks
xdevel2000