根据我的理解规则和 protected 变量的访问级别:
如果是同一个包
class A {
protected int =200;
}
class B extends A {
B 是 B 的引用变量
B.i 覆盖 B 类中 i 的值
b.i = 400;
a 是 A 的引用变量
a.i 将始终打印 200
}
class C extends B {
c 是 C 的引用变量 c.i 覆盖类 C 中 i 的值
c.i = 500;
a 是 A 的引用变量 a.i 将始终打印 200
}
结论:类 A 的 protected 成员在所有类的同一包中都是公共(public)的。
如果不同的包使用A
这里A和D不在同一个包中
class D extends A {
System.out.print(a.i);
以上语句将抛出编译时错误
这里 a.i 不可访问,i 现在在 A 中是私有(private)的
您只能将 i 与 D 的 ref 变量一起使用
System.out.print(d.i);
//no error
}
class E extends D {
System.out.print(a.i);
以上语句将抛出编译时错误
这里a.i是不可访问的,i现在在A中是私有(private)的
System.out.print(d.i);
以上语句将抛出编译时错误
这里 d.i 是不可访问的,i 现在在 D 中是私有(private)的
您只能将 i 与 E 的 ref 变量一起使用
System.out.print(e.i);
没有错误
}
结论:类 A 的 protected 成员在其直接子类的其他包中表现为私有(private)变量。
任何人都可以给我有关 protected 变量的访问级别的更多详细信息吗?
最佳答案
你试过吗official Java tutorial ,这对 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.
或者,如果您有并且仍然有一些问题,请详细说明
关于java - 不同包中 protected 变量的角色和访问级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31636026/