java - 为什么保护字段对子类不可见?

标签 java class

<分区>

我有一个类:

package foo;
public abstract class AbstractClause<T>{
    protected T item;
    protected AbstractClause<T> next;
}

及其子类(在不同的包中):

package bar;
import foo.AbstractClause;

public class ConcreteClause extends AbstractClause<String>{

    public void someMethod(ConcreteClause c) {
        System.out.println(this.next);      // works fine
        System.out.println(c.next);         // also works fine
        System.out.println(this.next.next); // Error: next is not visible
    }
}

为什么?

最佳答案

似乎如果子类在不同的包中,那么方法只能访问自己 protected 实例字段,而不能访问同一类的其他实例的字段。因此 this.lastthis.next 可以工作,因为它们访问 this 对象的字段,但是 this.last.nextthis.next.last 将不起作用。

public void append(RestrictionClauseItem item) {
    AbstractClause<Concrete> c = this.last.next; //Error: next is not visible
    AbstractClause<Concrete> d = this.next; //next is visible!
    //Some other staff
}

编辑 - 我不太对。无论如何感谢您的支持:)

我尝试了一个实验。我有这个类:

public class Vehicle {
    protected int numberOfWheels;
}

而这个在不同的包装中:

public class Car extends Vehicle {

  public void method(Car otherCar, Vehicle otherVehicle) {
    System.out.println(this.numberOfWheels);
    System.out.println(otherCar.numberOfWheels);
    System.out.println(otherVehicle.numberOfWheels); //error here!
  }
}

所以,重要的不是this。我可以访问同一类的其他对象的 protected 字段,但不能访问父类(super class)型对象的 protected 字段,因为父类(super class)型的引用可以包含任何对象,而不是 Car 的必要子类型(如 Bike ) 和 Car 无法访问由 Vehicle 的不同类型继承的 protected 字段(它们只能被扩展类及其子类型访问)。

关于java - 为什么保护字段对子类不可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30939056/

相关文章:

java - IntelliJ 使用错误的 JDK 版本从 POM 导入项目

java - 使用我自己的类作为输出值MapReduce Hadoop时,Reducer不会调用reduce方法

java - 当使用 Hibernate ORM 时,我应该先建模类图还是数据库图?

java - 以编程方式更改 Spring Boot 属性

java - JBoss 服务器上的 Java 应用程序中的 "Main loop"

c++ - 这怎么可能在 C++ 中使用?

powershell - 如何从单独的 ps1 文件访问自定义 PowerShell 5.0 类

C++成员函数和构造函数问题

java - 使用 map 检查是否包含数组。但不起作用

c++ - 如何使用字符串返回一个指向对象的唯一指针 vector 的迭代器来查找对象?