Java 修饰符
四种访问控制修饰符与 static、final、abstract、synchronized 等非访问修饰符。
Key Points访问范围从小到大:private < default < protected < public;final 修饰变量不可改、方法不可重写、类不可继承。
访问控制修饰符
Four modifiers decide visibility. default is not a keyword but the state when you write nothing — visible within the same package only.
| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
| private | ✔ | ✘ | ✘ | ✘ |
| default | ✔ | ✔ | ✘ | ✘ |
| protected | ✔ | ✔ | ✔ | ✘ |
| public | ✔ | ✔ | ✔ | ✔ |
Java
public class Access {
private int a = 1;
int b = 2;
protected int c = 3;
public int d = 4;
public static void main(String[] args) {
Access o = new Access();
System.out.println(o.a + o.b + o.c + o.d);
}
}Output
10非访问修饰符
static makes a member belong to the class, final freezes a variable, method or class, abstract declares an unimplemented method, synchronized locks a method for thread safety, and transient skips a field during serialization.
| Modifier | Applies to | Effect |
|---|---|---|
| static | field / method / block | Belongs to the class |
| final | field / method / class | No reassign / override / extend |
| abstract | class / method | Must be implemented by subclass |
| synchronized | method / block | Mutual exclusion lock |
| transient | field | Excluded from serialization |
| volatile | field | Always read from main memory |
Java
public class NonAccess {
static int counter = 0;
final int limit = 5;
static void inc() {
counter++;
}
public static void main(String[] args) {
inc();
inc();
System.out.println(counter);
System.out.println(new NonAccess().limit);
}
}Output
2
5final on a reference forbids reassignment, not mutation: final List<String> list still allows list.add(...).访问控制修饰符
四个修饰符决定成员能被谁访问。default 不是关键字,而是「什么都不写」时的默认状态,只有同包可见。
| 修饰符 | 同类 | 同包 | 子类 | 其他 |
|---|---|---|---|---|
| private | ✔ | ✘ | ✘ | ✘ |
| default | ✔ | ✔ | ✘ | ✘ |
| protected | ✔ | ✔ | ✔ | ✘ |
| public | ✔ | ✔ | ✔ | ✔ |
Java
public class Access {
private int a = 1;
int b = 2;
protected int c = 3;
public int d = 4;
public static void main(String[] args) {
Access o = new Access();
System.out.println(o.a + o.b + o.c + o.d);
}
}Output
10非访问修饰符
static 让成员属于类;final 冻结变量、方法或类;abstract 声明未实现的抽象方法;synchronized 给方法加锁保证线程安全;transient 跳过序列化。
| 修饰符 | 作用对象 | 效果 |
|---|---|---|
| static | 字段 / 方法 / 代码块 | 属于类 |
| final | 字段 / 方法 / 类 | 不可改 / 重写 / 继承 |
| abstract | 类 / 方法 | 子类必须实现 |
| synchronized | 方法 / 代码块 | 互斥锁 |
| transient | 字段 | 不参与序列化 |
| volatile | 字段 | 总从主内存读取 |
Java
public class NonAccess {
static int counter = 0;
final int limit = 5;
static void inc() {
counter++;
}
public static void main(String[] args) {
inc();
inc();
System.out.println(counter);
System.out.println(new NonAccess().limit);
}
}Output
2
5final 修饰引用时,引用不能改指向,但对象内部仍可变 —— final List<String> list 依然可以 list.add(...)。