Java – Final修饰符到底修饰了什么

Categories: Java; Tagged with: ; @ February 5th, 2009 15:09

Final 修饰符在修饰基本数据类型时, 能保证其值不被改变, 但在修饰对象时, Final保证引用本身不变, 而不能保证引用对象的不变.

如下:

		
		final StringBuilder sb = new StringBuilder("Final SB");
		System.out.println(sb.toString());
		StringBuilder sb2 = new StringBuilder(" USB");
		//sb = sb2 //试图修改sb的引用. 编译出错, final变量不可被更改
		sb.append(sb2); //修改sb引用对象, final不能保证引用对象不被改变. 编译通过.
		System.out.println(sb.toString());

输出:

Final SB

Final SB USB



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.