参考: http://liyuan2005.iteye.com/blog/209206
1.
当你在类中定义变量时,在其前面加上final关键字,那便是说,这个变量一旦被初始化便不可改变,这里不可改变的意思对基本类型来说是其值不可变,而对于对象变量来说其引用不可再变 。
2.
其初始化可以在两个地方,一是其定义处,也就是说在final变量定义时直接给其赋值,二是在构造函数中 。这两个 地方只能选其一,要么在定义时给值,要么在构造函数中给值,不能同时既在定义时给了值,又在构造函数中给另外的值。
3.
引用对象 can never be changed to point to another object.
However, 引用对象 can be modified;
public class Bat {
final double PI = 3.14; // 在定义时便给址值
final int i; //称为"Blank final",因为要在构造函数中进行初始化,所以此处便不可再给值
final List list; // 此变量也与上面的一样
Bat() {
//PI=3.14; 不能同时既在定义时给了值,又在构造函数中给另外的值
i = 100;
list = new LinkedList();
}
Bat(int ii, List l) {
i = ii;
list = l;
}
public static void main(String[] args) {
// 1. 默认的构造函数
Bat b = new Bat();
System.out.println(b.i + "->" + b.list.getClass());
// 不论是i的 值或是list的类型,一旦初始化,无法再更改
// b.i=25;
// b.list=new ArrayList();
// 2.带参数的构造函数
Bat b2 = new Bat(10, new ArrayList());
System.out.println(b2.i + "->" + b2.list.getClass());
// 可以通过重新初始化来指定i的值或list的类型
//引用对象 can never be changed to point to another object.
//However, the object can be modified;
b2.list.add("aaa");
}
}