父类中的受保护方法在其他包的子类中可见吗? [英] Is protected method in super class visible in sub class in a different package?

查看:179
本文介绍了父类中的受保护方法在其他包的子类中可见吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这看起来很傻,但是我真的很困惑。请参见以下代码:

It seems very silly, but I am really confused. Please see below code:

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文档和,受 受保护的成员也可以在另一个包的子类中看到 。因此fun()应该在第二包的子类中可见。那为什么出错呢?

I have read from oracle doc and here as well, that protected members are visible in the sub class in another package also. So fun() should be visible in SubClass in package two. Then why the error?

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

Am I terribly missing something very obvious?

推荐答案

Java语言规范


对象的受保护成员或构造函数可以从仅通过以下方式声明的包外部访问:负责该对象实现的代码。

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.

这意味着,如果您在在原始示例中,每个对象都可以在自身上调用父类的受保护方法,而不能在其他对象上调用。

What that means is that if you're writing a subclass outside the package of the original class, each object can call the superclass's protected methods on itself, but not on other objects.

在您的示例中,因为 s 是与 this 不同的对象,您不能调用 s.fun()。但是该对象将能够自行调用 fun 方法-使用 this.fun()或仅使用 fun()

In your example, because s is a different object from this, you can't call s.fun(). But the object would be able to call the fun method on itself - with this.fun() or just fun().

这篇关于父类中的受保护方法在其他包的子类中可见吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆