简体   繁体   English

无法访问子 class 中的受保护方法

[英]Can not access protected method in the sub class

Why I can not use clone() method in public class Object ?为什么我不能在public class Object中使用 clone() 方法? clone() method is protected int the Object class and all classed are sub classes of Object class. BC clone()方法在 Object class 中protected ,所有分类都是 Object ZA2F21ED4F8EBC6DZ4 的子类protected methods can be accessed from sub classes and from classed in the same package.可以从子类和同一个 package 中的类访问protected的方法。 So why I have such an error?那么为什么我有这样的错误?

public class Test
{
    public static void main(String[] args)
    {
        Test2 c1 = new Test2();
        Test2 c2 = (Test2) c1.clone(); // error: clone() has protected access in java.lang.Object
    }
}

class Test2 implements Cloneable
{

}

clone() is in java.lang.Object , and your Test class is not in the java.lang package. clone() is in java.lang.Object , and your Test class is not in the java.lang package. In other words, protected doesn't quite mean what you think it means.换句话说, protected并不完全意味着你认为它的意思。

The fix is trivial.修复是微不足道的。 add this to your Test2:将此添加到您的 Test2:

class Test2 implements Cloneable {
    @Override public Test2 clone() {
        return (Test2) super.clone();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM