转载请注明出处
http://blog.csdn.net/pony_maggie/article/details/44317505
作者:小马
final类型的成员变量
class Value
{
int i = 1;
}
public class FinalData
{
final int i1 = 9;
static final int VAL_TWO = 99;
public static final int VAL_THREE = 39;
final int i4 = (int)(Math.random()*20);
static final int i5 = (int)(Math.random()*20);
final int i6;
Value v1 = new Value();
final Value v2 = new Value();
static final Value v3 = new Value();
//arrays
final int[] a = {1, 2, 3, 4, 5, 6};
public FinalData()
{
i6 = 0;
}
public void print(String id)
{
System.out.println(id + ": " + "i4 = " + i4 +
", i5 = " + i5);
}
/**
* @param args
*/
public static void main(String[] args)
{
FinalData fd1 = new FinalData();
//fd1.i1++; //error: can't change value
fd1.v2.i++; //object is not constant.
fd1.v1 = new Value(); // ok, not final
for(int i = 0; i < fd1.a.length; i++)
{
fd1.a[i]++;//object is not constant.
//fd1.v2 = new Value(); // can't change reference.
//fd1.v3 = new Value(); // can't change reference.
//fd1.a = new int[3];
fd1.print("fd1");
System.out.println("creating new finalData");
FinalData fd2 = new FinalData();
fd1.print("fd1");
fd2.print("fd2");
}
}
}
fd1: i4 = 0, i5 = 11
creating new finalData
fd1: i4 = 0, i5 = 11
fd2: i4 = 18, i5 = 11
fd1: i4 = 0, i5 = 11
creating new finalData
fd1: i4 = 0, i5 = 11
fd2: i4 = 9, i5 = 11
fd1: i4 = 0, i5 = 11
creating new finalData
fd1: i4 = 0, i5 = 11
fd2: i4 = 10, i5 = 11
fd1: i4 = 0, i5 = 11
creating new finalData
fd1: i4 = 0, i5 = 11
fd2: i4 = 7, i5 = 11
fd1: i4 = 0, i5 = 11
creating new finalData
fd1: i4 = 0, i5 = 11
fd2: i4 = 1, i5 = 11
fd1: i4 = 0, i5 = 11
creating new finalData
fd1: i4 = 0, i5 = 11
fd2: i4 = 4, i5 = 11
fd1.v2.i++
这一行表明,对于v2只是引用不能更改,但是它的值还是可以改的,也就是说,reference是常量,object不是。同样的原量也适用于数组a,毕竟数组在java里也是引用。
未完待续。