gpt4 book ai didi

java - 为什么 protected 访问修饰符在与静态一起使用时与与非静态一起使用时的工作方式不同

转载 作者:行者123 更新时间:2023-11-30 06:11:03 26 4
gpt4 key购买 nike

通常情况下,当我们对类中的字段使用 protected 时,如果子类位于不同的包中,则其子类无法使用基类的引用来访问它。那是真实的 。但是我发现当在字段中添加静态关键字时,它的行为会有所不同。它变得易于访问。这怎么可能 。有没有人知道答案。

package com.car;

public class Car {

static protected int carNo=10;

}


package com.bmw;
import com.car.*;

public class BMW extends Car {

public static void main(String[] args) {
//Its accessible here
System.out.println(new Car().carNo);
}
}

最佳答案

6.6.2.1. Access to a protected Member

Let C be the class in which a protected member is declared. Access is permitted only within the body of a subclass S of C.

In addition, if Id denotes an instance field or instance method, then:

If the access is by a qualified name Q.Id, where Q is an ExpressionName, then the access is permitted if and only if the type of the expression Q is S or a subclass of S.

If the access is by a field access expression E.Id, where E is a Primary expression, or by a method invocation expression E.Id(. . .), where E is a Primary expression, then the access is permitted if and only if the type of E is S or a subclass of S.

来源:https://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6.2.1

public class BMW extends Car {
public static void main(String[] args) {
System.out.println(new BMW().carNo);
}
}

是有效的,因为 new BMW() 是 Car 的子类,即使在不同的包中也是如此。

public class BMW extends Car {
public static void main(String[] args) {
System.out.println(new Car().carNo);
}
}

无效,因为 new Car() 不是 Car 的子类,并且它在不同的包中被调用。 (如果类是其自身的子类,请参阅 Java: Is a class a subclass of itself? 的讨论)

现在,如果 carNo 是静态的,这是合法的

System.out.println(new Car().carNo);

然而,这里正确的语法是

System.out.println(Car.carNo);

因为 carNo 不是实例字段,因为它是静态的。事实上,即使这样也可以在 BMW 内部使用

System.out.println(carNo);

因为

Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared

https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.2 所述

关于java - 为什么 protected 访问修饰符在与静态一起使用时与与非静态一起使用时的工作方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34768085/

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