编程语言
首页 > 编程语言> > java – 超类中的受保护方法在不同包中的子类中是否可见?

java – 超类中的受保护方法在不同包中的子类中是否可见?

作者:互联网

参见英文答案 > What is the difference between public, protected, package-private and private in Java?                                    25个
这看起来很傻,但我真的很困惑.请看下面的代码:

package com.one;
public class SuperClass {
    protected void fun() {
        System.out.println("base fun");
    }
}
----
package com.two;
import com.one.SuperClass;
public class SubClass extends SuperClass{
    public void foo() {
        SuperClass s = new SuperClass();
        s.fun(); // Error Msg: Change visibility of fun() to public 
    }
}

我也从oracle doc和here中读到,受保护的成员也可以在另一个包的子类中看到.所以fun()应该在包2中的SubClass中可见.那为什么错误?

我非常想念一些非常明显的东西吗?

解决方法:

Java Language Specification

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

这意味着如果你在原始类的包之外编写一个子类,每个对象都可以调用超类的受保护方法,而不是其他对象.

在您的示例中,因为s是与此不同的对象,所以不能调用s.fun().但是该对象可以通过this.fun()或fun()调用自己的有趣方法.

标签:superclass,java,inheritance,access-modifiers,protected
来源: https://codeday.me/bug/20190929/1832980.html