无法访问子类中的受保护方法。

huangapple go评论59阅读模式
英文:

Can not access protected method in the sub class

问题

为什么我不能在 ```public class Object``` 中使用 ```clone()``` 方法?```clone()``` 方法在 Object 类中是 ```protected``` 的,而所有的类都是 Object 类的子类。```protected``` 方法可以被子类和同一包中的类访问。那么为什么会出现这样的错误?

public class Test
{
public static void main(String[] args)
{
Test2 c1 = new Test2();
Test2 c2 = (Test2) c1.clone(); // 错误:clone() 在 java.lang.Object 中具有 protected 访问权限
}
}

class Test2 implements Cloneable
{

}


<details>
<summary>英文:</summary>

Why I can not use clone() method in ```public class Object```? ```clone()``` method is ```protected``` int the Object class and all classed are sub classes of Object class. ```protected``` methods can be accessed from sub classes and from classed in the same package. 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
{

}


</details>


# 答案1
**得分**: 0

`clone()` 方法位于 `java.lang.Object` 中,而您的 `Test` 类不在 `java.lang` 包中。换句话说,`protected` 并不完全意味着您所认为的那样。

修复方法很简单,将以下内容添加到您的 `Test2` 类中:

```java
class Test2 implements Cloneable {
    @Override
    public Test2 clone() {
        return (Test2) super.clone();
    }
}
英文:

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.

The fix is trivial. add this to your Test2:

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

huangapple
  • 本文由 发表于 2020年7月30日 23:17:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/63176282.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定