Java Final变量
Java中的final变量只能被赋值一次,我们可以在声明中或之后赋值。
final int i = 10;
i = 30; // Error because i is final.
Java中的 final 变量是一个在声明时没有初始化的final变量。下面是一个关于空白final的简单例子。
// A simple blank final example
final int i;
i = 30;
如何向对象的空白最终成员赋值? 必须在构造函数中赋值。
// A sample Java program to demonstrate use and
// working of blank final
class Test {
// We can initialize here, but if we initialize here,
// then all objects get the same value. So we use blank
// final
final int i;
Test(int x)
{
// Since we have already declared i as final above,
// we must initialize i in constructor. If we remove
// this line, we get compiler error.
i = x;
}
}
// Driver Code
class Main {
public static void main(String args[])
{
Test t1 = new Test(10);
System.out.println(t1.i);
Test t2 = new Test(20);
System.out.println(t2.i);
}
}
输出
10
20
如果我们在类中有多个构造函数或重载构造函数,那么空白最终变量必须在所有的构造函数中被初始化。然而,构造函数链可以用来初始化空白最终变量。
// A Java program to demonstrate that we can
// use constructor chaining to initialize
// final members
class Test
{
final public int i;
Test(int val) { this.i = val; }
Test()
{
// Calling Test(int val)
this(10);
}
public static void main(String[] args)
{
Test t1 = new Test();
System.out.println(t1.i);
Test t2 = new Test(20);
System.out.println(t2.i);
}
}
输出
10
20
空白的最终变量被用来创建不可变的对象(一旦初始化,其成员就不能改变的对象)。