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

问题描述

限时删除!!

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

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文档和说

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

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().

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

1403页,肝出来的..

09-06 08:28