桥接方法解释

发布于 2024-09-06 04:03:18 字数 464 浏览 5 评论 0原文

如果我重写克隆方法,编译器会创建一个桥接方法 保证正确的多态性(这是反编译的类),

class Point
{

    Point()
    {
    }

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

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

因此当调用克隆方法时,将调用桥接方法,并在其内部调用正确的克隆方法。但我的问题是,当桥接方法被调用时,虚拟机如何表示它必须调用 Point clone() 而不是它自己???

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???

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

会发光的星星闪亮亮i 2024-09-13 04:03:18

此代码无法使用 java 1.6 编译。 Java 中的方法签名不包括返回类型...并且不能有重复的方法签名。

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.

半边脸i 2024-09-13 04:03:18

你不能这样做,它不会编译,因为你有两个具有相同名称和相同参数的方法(在本例中没有),并且如果你调用 somePoint.clone() 则不清楚哪一个是的意思。

你应该做类似的事情:

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

编辑:一些更好的点:
你的类应该实现可克隆接口,否则 super.clone() 将给出异常。 Object 类中的clone() 方法返回当前对象的浅表副本(它的运行时类将与调用clone 方法的对象的运行时类相同)。然后,您的工作是对该对象执行任何特定于类的操作(例如克隆对其他对象的引用),然后返回它。返回类型可以是您自己的类而不是 Object,它仍然会覆盖 Object.clone() (或任何其他 ParentClass.clone())方法。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文