java - 访问 protected 成员时出错

标签 java oop inheritance package protected

<分区>

//Filename: A.java
package packageA;
public class A {
    protected int x;
}

//Filename B.java
package packageB;
import packageA.A;

public class B extends A {
    void action(A ob1, B ob2, C ob3) {
        x = 10;
        ob1.x = 10;   // <-- error here
        ob2.x = 10;
        ob3.x = 10;
    }

public class C extends B {
    void action(A ob1, B ob2, C ob3) {
        x = 10;
        ob1.x = 10;    // <-- error here
        ob2.x = 10;    // <-- error here
        ob3.x = 10;
    }

所以,我在阅读 Java 中的 protected 用法时遇到了这个问题。 A.javaB.java 是单独的文件,如您所见,保存在单独的包中。编译 B.java 时,我得到 3 个错误,表明 xA 中具有 protected 访问权限。有人可以解释为什么即使在扩展类 A 之后我仍会出错吗?

最佳答案

不允许您通过父类(super class)型引用访问 protected 成员。参见 Java Language Specification, section 6.6.2: Details on Protected Access .

A compile-time error occurs in the method delta here: it cannot access the protected members x and y of its parameter p, because while Point3d (the class in which the references to fields x and y occur) is a subclass of Point (the class in which x and y are declared), it is not involved in the implementation of a Point (the type of the parameter p). The method delta3d can access the protected members of its parameter q, because the class Point3d is a subclass of Point and is involved in the implementation of a Point3d.

关于java - 访问 protected 成员时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33041154/

相关文章:

java - 调用 super 方法是否有意义?

java - 一起运行时 Android JUnit 测试挂起

javascript - 从 for-in 循环获取属性名称背后的简单理论?

java - 如果类是类型,那么它们可以保存什么类型的数据?

Javascript:仍然对 instanceof 运算符感到困惑

c++ - 为什么基指针只能在公共(public)继承下指向派生对象?

java - mybatis映射中如何定义复合主键

java - 如何查找字符串数组中大写字符的数量?

java - new in 循环会删除旧对象吗?

C++继承问题