我们可以控制类成员变量和方法的访问级别通过访问说明符。
Java的访问说明符是public,private,protected和默认访问级别。
级别
- 公共类成员可以通过任何其他代码访问。
- 私有类成员只能在其类中访问。
- 默认访问类成员没有访问说明符。 类的默认功能可以在同一个包中的任何类访问。
- 类的受保护特性可用于同一个包(如默认)中的所有类及其子类。
受保护的功能比默认功能更容易访问。
要了解公共和私人访问的影响,请考虑以下程序:
class Test {
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i) {
c = i;
}
int getc() {
return c;
}
}
public class Main {
public static void main(String args[]) {
Test ob = new Test();
ob.a = 1;
ob.b = 2;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a +
" " + ob.b + " " + ob.getc());
}
}
输出:
成员访问和继承
子类不能访问超类的私有成员。例如,考虑下面的简单类层次结构。如果尝试编译以下程序,您将收到错误消息。
class A {
private int j; // private to A
}
class B extends A {
int total;
void sum() {
total = j; // ERROR, j is not accessible here
}
}
输出:
Java的访问矩阵
下表显示了Java的访问矩阵。是意味着无障碍,没有意义无法访问。
位置 | 私人的 | 无修饰符 | 保护 | 公开 |
---|---|---|---|---|
相同类 | Yes | Yes | Yes | Yes |
相同的包子类 | No | Yes | Yes | Yes |
相同的包非子类 | No | Yes | Yes | Yes |
不同的包子类 | No | No | Yes | Yes |
不同的包非子类 | No | No | No | Yes |
访问修饰符及其目标
并非所有修改器都可以应用于所有功能。顶级类可能不受保护。方法可能不是短暂的。静态可以将其应用于自由浮动代码块。
下表显示了功能和修改器的所有可能组合。yes表示我们可以使用该修饰符来控制对应实体的访问。
修饰符 | 类 | 变量 | 方法 | 构造函数 | 代码块 |
---|---|---|---|---|---|
public | yes | yes | yes | yes | no |
protected | no | yes | yes | yes | no |
empty accessor | yes | yes | yes | yes | yes |
private | no | yes | yes | yes | no |
final | yes | yes | yes | no | no |
abstract | yes | no | yes | no | no |
static | no | yes | yes | no | yes |
native | no | no | yes | no | no |
transient | no | yes | no | no | no |
volatile | no | yes | no | no | no |
synchronized | no | no | yes | no | yes |