Java编程中的常见误区及Android平台适用性解析
1. 引用不可变性与被引用对象不可变性的区别
1.1 概念解析
不可变性有助于安全推理,共享不可变对象时不会有被接收方修改的风险。但程序员常错误认为,声明字段或变量为 final 就能使被引用对象不可变。实际上,对于基本类型变量,声明为 final 可防止初始化后值被修改;而对于引用类型变量, final 仅使引用本身不可变,被引用对象的字段仍可能可变。
1.2 代码示例
1.2.1 非合规代码示例(可变类, final 引用)
class Point {
private int x;
private int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
void set_xy(int x, int y) {
this.x = x;
this.y = y;
}
void print_xy() {
System.out.println("the value x is: " + this.x);
System.out.println("the value y is: " + this.y);
}
}
public class PointCaller {
public stat
超级会员免费看
订阅专栏 解锁全文
1万+

被折叠的 条评论
为什么被折叠?



