gpt4 book ai didi

java - 为什么我允许 "direct access"到对象的 protected 字段,该对象的类是在不同的包中定义的?

转载 作者:行者123 更新时间:2023-12-02 05:55:42 25 4
gpt4 key购买 nike

Main.java,主包:

package pkgs.main;
import pkgs.test.B;

// Just some method inside the "main class"
void method() {
B b = new B();
b.x ++; // <--- why is this allowed?
}

A.java,主包:

package pkgs.main;

public class A {
protected int x;
}

B.java,测试包:

package pkgs.test;
import pkgs.main.A;

public class B extends A {
}

编辑:

看待这个问题的另一种方式如下。我将在现有示例代码中添加两行额外的代码:

Main.java,主包:

// Just some method inside the "main class"
void method() {
B b = new B();
b.x ++; // <--- why is this allowed?

b.y ++; // (Additional code) Compilation ERROR, which is correct.
}

B.java,测试包:

public class B extends A {
protected int y; // (Additional code) protected field;
// access to it is disallowed inside the
// "main calling class" above.
}

最佳答案

由于 B 扩展了 A , protected 字段也允许访问它的子级。

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

请优先阅读 Controlling Access to Members of a Class

Modifier    Class   Package Subclass    World
---------------------------------------------

protected Y Y **Y** N

关于java - 为什么我允许 "direct access"到对象的 protected 字段,该对象的类是在不同的包中定义的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23108727/

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