为什么在Java中从子类访问受保护的方法时会出现编译错误?

为什么在Java中从子类访问受保护的方法时会出现编译错误?,java,inheritance,subclass,protected,Java,Inheritance,Subclass,Protected,我读过关于Java中受保护修饰符的内容,这些字段可以在同一个包和子类中访问 package abstraact.concept; import com.Parent; public class BaseParent extends Parent{ public void printNum() { Parent p = new Parent(); p.print(); /** Getting error

我读过关于Java中受保护修饰符的内容,这些字段可以在同一个包和子类中访问

package abstraact.concept;

import com.Parent;

    public class BaseParent extends Parent{

        public void printNum()
        {
            Parent p = new Parent();
            p.print(); /** Getting error here */
                    // The method print() from the type Parent is not visible
        }



        public static void main(String[] args) {
            BaseParent pp = new BaseParent();
            pp.printNum();

        }
    }
现在我已经写了一些代码

package com;

public class Parent {

    protected void print()
    {
        System.out.println("dFDF");
    }
}
现在是子类

package abstraact.concept;

import com.Parent;

    public class BaseParent extends Parent{

        public void printNum()
        {
            Parent p = new Parent();
            p.print(); /** Getting error here */
                    // The method print() from the type Parent is not visible
        }



        public static void main(String[] args) {
            BaseParent pp = new BaseParent();
            pp.printNum();

        }
    }
为什么我会出错? 由于受保护的方法/变量可以从子类访问。

调用
super.print()
而不是声明一个新的
父对象

这是
Java
中常见的“悖论”,实际上根本不是悖论。简单地说,由于语言的安全性(可见性)规则,无法通过另一个包中的对象引用访问受保护的方法

package abstraact.concept;

import com.Parent;

    public class BaseParent extends Parent{

        public void printNum()
        {
            Parent p = new Parent();
            p.print(); /** Getting error here */
                    // The method print() from the type Parent is not visible
        }



        public static void main(String[] args) {
            BaseParent pp = new BaseParent();
            pp.printNum();

        }
    }
一旦声明了一个新对象,它所拥有(或允许)的可见性就由代码所属的包控制,而不是由继承层次结构控制

召唤

super.print();


将起作用。

如果包不同,则无法访问受保护的方法。您可以按以下方式访问此方法:

 BaseParent pp = new BaseParent();
 pp.print();


试着仔细理解这句话。Protected仅在派生类中可见。对于继承来说也是如此。但是,当您创建父类型的对象时,您没有使用继承。这意味着父级不是在那里派生的,父级的功能受到保护。但是,如果使用
super.print()
它将通过继承引用父级并获得该函数

因此,您的解决方案是替换:

Parent p = new Parent();
p.print();


将print方法声明为protected允许子类BaseParent继承它

当BaseParent中的代码引用其自己(继承的)版本的“print”时,这是允许的,因为它已成为该子类的一部分。 但是,子类仍然无法引用父类自己的方法版本(尽管在同一个包中会否决此操作),因为“protected”关键字只允许其他包中的子类继承和使用自己的方法版本

经过一段时间的努力,我终于明白了为什么会出现错误,这就是我对它的看法

第6.6.2节中的Oracle文档以自己的方式说明了这一点:

对象的受保护成员或构造函数可以从包的外部访问,在包中它只能由负责该对象实现的代码声明


因此BaseParent只负责其自身继承的打印方法ID,而不是父类中的原始对象。

show方法在哪里?可能重复的?请详细说明或给我链接,我可以在其中阅读它吗?基本思想是父对象引用与声明它的地方的任何其他对象引用具有相同的访问限制。要利用层次结构,您必须专门使用this或super。@思考者:在谷歌上搜索一下继承和组合,了解两者之间的区别。还要了解,对象的处理方式与所有其他对象相同,层次结构的处理方式也很特殊。
super.print();