Java关键字Final的变与不变

     

     Final 修饰字段时,之前一个模糊的概念是它使变量不可变,然而下面的情况呢?

     可以看见,被 final 修饰后,变量还是改变了,何以如此?见注释。 

 

 

package javaDetail.finalKeyWord;

public class AboutFinal {

	// here we use the final key word,but find that it still can be changed.
	static final StringBuffer sb = new StringBuffer("hello,world");

	/**
	 * you will find that sb's value has been changed,why,isn't it that the
	 * variable "sb" is final,and can not be changed.
	 * <p>
	 * "final" 's effect on reference type is :we keep the variable's reference
	 * unchangeable(it always point to the same place in memory),while,as for
	 * the object it referred to,we can't promise that it will not change.
	 * <p>
	 * so,here the thing that has been changed is the object this
	 * pointer(variable,I think in java,reference type variable is quite like
	 * pointer) point to.The variable it self,has not been changed.
	 * <p>
	 * while,if you try to change the final variable(as the line that has been
	 * commented try to do),you will get the error : The final field Final.sb
	 * cannot be assigned.
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		// sb = new StringBuffer("hello,world");
		sb.append("hello,world");

		System.out.println(sb);//the result is :[hello,worldhello,world] do not you feel surprised?
	}
}

 

 

        实际上是:

        final 修饰Object时,只能确保引用不变,即至始至终指向同一片内存单元(好像指针啊),有点从一而终的意思,但要命的是,不能保证我指向的那家伙就会不变,这儿就是如此,我始终指向的是那一处不错,可是那儿的StringBuffer的值 却变了,那也是没办法的事情。

 

    另外注意main()函数中被注释掉的第一行

                         //sb = new StringBuffer("hello,world");

    它试图让sb指向另一处地址,这就是试图修改sb的指向了,那怎么能行?试一下,发现确实不行,会有编译错误。

 

 

 

 

你可能感兴趣的:(java)