gpt4 book ai didi

java - 为什么 protected 静态字段在 Java 的不同类中可见

转载 作者:搜寻专家 更新时间:2023-10-31 19:54:36 24 4
gpt4 key购买 nike

下面是代码:

package ab:
public class A {
protected static int var = 10;
protected int var2 = 20;
}

    package cd;
public class C extends A {
A test;

public C(){
test = new A();
}

void printValues(){
System.out.println(A.var); //this is perfectly visible
System.out.println(test.var2); // here I get error saying var2 is not visible
}
}

我不明白为什么静态保护字段可以通过不同包中的 A 访问...

最佳答案

因为一个 protected 成员可以从任何包中的子类访问这一事实广为人知,我正在回答你问题的另一面:为什么 protected 实例字段对子类可见?

像往常一样,寻找权威答案的地方是 Java 语言规范,在本例中为 Section 6.6.2 .我引用了那里找到的例子,因为它比前面的法律术语更容易理解。

TL;DR: 最好的理解方式是:protected 是一个内部继承类。从其所有子类的角度来看,A.var2 的行为类似于每个子类单独私有(private)成员,而不是父类(super class)的成员。所有这一切都已到位,因为 protected 旨在用于为扩展而设计的类中,以便子类可以访问那些被认为是扩展类的公共(public) API 的部分,但不能用于客户端类(class)的。

为了完成您的示例系列,我提交了另外两个示例:

System.out.println(this.var2);      // works---intended use of protected
System.out.println(((A)this).var2); // fails same as your test.var2

深思:)

Example 6.6.2-1. Access to protected Fields, Methods, and Constructors

Consider this example, where the points package declares:

package points;
public class Point {
protected int x, y;
void warp(threePoint.Point3d a) {
if (a.z > 0) // compile-time error: cannot access a.z
a.delta(this);
}
}

and the threePoint package declares:

package threePoint;
import points.Point;
public class Point3d extends Point {
protected int z;
public void delta(Point p) {
p.x += this.x; // compile-time error: cannot access p.x
p.y += this.y; // compile-time error: cannot access p.y
}
public void delta3d(Point3d q) {
q.x += this.x;
q.y += this.y;
q.z += this.z;
}
}

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.

The method delta could try to cast (§5.5, §15.16) its parameter to be a Point3d, but this cast would fail, causing an exception, if the class of p at run time were not Point3d.

A compile-time error also occurs in the method warp: it cannot access the protected member z of its parameter a, because while the class Point (the class in which the reference to field z occurs) is involved in the implementation of a Point3d (the type of the parameter a), it is not a subclass of Point3d (the class in which z is declared).

关于java - 为什么 protected 静态字段在 Java 的不同类中可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28798080/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com