在 Java 中,private 是访问修饰符,用于限制成员(变量、方法、构造器等)只能在同一个类内部访问。在实际开发中,关于 private 的常见错误主要集中在误用、误解访问范围、JSON/框架反射、继承误区等方面。下面按“场景 + 错误示例 + 正确做法”说明。
private 能被子类访问(最常见)class Parent {
private int age = 10;
}
class Child extends Parent {
void test() {
System.out.println(age); // 编译错误
}
}
private 不能被继承private 成员protected int age;
// 或提供 getter
public int getAge() { return age; }
private 方法能被外部类调用class User {
private void say() {}
}
User u = new User();
u.say(); // 编译错误
public / protected 方法间接调用private 字段class User {
private String name;
public String getName() {
return name; // 可能为 null
}
}
public User(String name) {
this.name = name;
}
class User {
private Long id;
// 没有 setter / 无参构造
}
Jackson / Fastjson 反序列化失败:
{ "id": 1 }
private Long id;
public void setId(Long id) {
this.id = id;
}
或:
@JsonProperty
private Long id;
private 能提高安全性(安全误区)private 字段外部改不了,所以安全
privateField f = obj.getClass().getDeclaredField("secret");
f.setAccessible(true);
f.set(obj, "hack");
✅ private 是封装,不是安全机制
private 构造器使用错误class Util {
private Util() {}
}
// 忘记防止反射创建
private Util() {
if (instance != null) {
throw new IllegalStateException();
}
}
class Outer {
private int x = 1;
class Inner {
void test() {
System.out.println(x); // OK
}
}
}
⚠️ 这是 Java 编译器特殊处理,不是普通访问规则
obj.privateMethod(); // 编译失败
package-privateprivate static int count;
✅ 合法
⚠️ 注意:所有实例共享
| 错误类型 | 是否编译错误 | 说明 |
|---|---|---|
| 子类访问 private | ✅ | 不可继承 |
| 外部调用 private 方法 | ✅ | 不可访问 |
| JSON 反序列化失败 | ❌(运行时) | 缺 setter |
| 认为 private 安全 | ❌(误解) | 可被反射 |
| private 构造器 | ✅/⚠️ | 单例需防反射 |
如果你愿意,我可以:
直接贴代码即可。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。