Java中用final来定义一个引用引用一个对象后就不能再被用来引用其他对象(基本数据类型也一样),但是允许引用的对象改变。举个例子来说:
上面的代码是允许的。因为str始终只引用了唯一的一个StringBuilder对象。所以输出结果为hello world。
如果代码这样写:
这个时候是不能通过编译的。
简单来说,final后的变量只能进行一次赋值,这次赋值可以发生在声明时,也可以在声明后。
final StringBuilder str = new StringBuilder("hello");
str.append(" world");
System.out.println(str);
上面的代码是允许的。因为str始终只引用了唯一的一个StringBuilder对象。所以输出结果为hello world。
如果代码这样写:
final StringBuilder str = new StringBuilder("hello");
str = new StringBuilder("hello world");
这个时候是不能通过编译的。
简单来说,final后的变量只能进行一次赋值,这次赋值可以发生在声明时,也可以在声明后。