Final 数据

对于原始类型,final使数值恒定不变,而用于对象引用,final使引用恒定不变。一旦引用被初始化指向一个对象,就无法对它进行改变以指向另一个对象。然而,对象其自身却是可以被修改的,Java并未提供使任何对象恒定不变的途径。(但你可以自己编写类以取得使对象恒定不变的效果。)这一限制同样适用数组,它也是对象。

下面是一个用以说明final数据成员的示例:

//: c06:FinalData.java
// The effect of final on fields.
import com.bruceeckel.simpletest.*;
import java.util.*;

class Value {
	int i; // Package access

	public Value(int i) {
		this.i = i;
	}
}

public class FinalData {
	private static Test monitor = new Test();
	private static Random rand = new Random();
	private String id;

	public FinalData(String id) {
		this.id = id;
	}

	// Can be compile-time constants:
	private final int VAL_ONE = 9;
	private static final int VAL_TWO = 99;
	// Typical public constant:
	public static final int VAL_THREE = 39;
	// Cannot be compile-time constants:
	private final int i4 = rand.nextInt(20);
	static final int i5 = rand.nextInt(20);
	private Value v1 = new Value(11);
	private final Value v2 = new Value(22);
	private static final Value v3 = new Value(33);
	// Arrays:
	private final int[] a = { 1, 2, 3, 4, 5, 6 };

	public String toString() {
		return id + ": " + "i4 = " + i4 + ", i5 = " + i5;
	}

	public static void main(String[] args) {
		FinalData fd1 = new FinalData("fd1");
		// ! fd1.VAL_ONE++; // Error: can't change value
		fd1.v2.i++; // Object isn't constant!
		fd1.v1 = new Value(9); // OK -- not final
		for (int i = 0; i < fd1.a.length; i++)
			fd1.a[i]++; // Object isn't constant!
		// ! fd1.v2 = new Value(0); // Error: Can't
		// ! fd1.v3 = new Value(1); // change reference
		// ! fd1.a = new int[3];
		System.out.println(fd1);
		System.out.println("Creating new FinalData");
		FinalData fd2 = new FinalData("fd2");
		System.out.println(fd1);
		System.out.println(fd2);
		monitor.expect(new String[] { "%% fd1: i4 = \\d+, i5 = \\d+",
				"Creating new FinalData", "%% fd1: i4 = \\d+, i5 = \\d+",
				"%% fd2: i4 = \\d+, i5 = \\d+" });
	}
} // /:~

 

//: c06:BlankFinal.java
// "Blank" final fields.
class Poppet {
	private int i;

	Poppet(int ii) {
		i = ii;
	}
}

public class BlankFinal {
	private final int i = 0; // Initialized final
	private final int j; // Blank final
	private final Poppet p; // Blank final reference
	// Blank finals MUST be initialized in the constructor:

	public BlankFinal() {
		j = 1; // Initialize blank final
		p = new Poppet(1); // Initialize blank final reference
	}

	public BlankFinal(int x) {
		j = x; // Initialize blank final
		p = new Poppet(x); // Initialize blank final reference
	}

	public static void main(String[] args) {
		new BlankFinal();
		new BlankFinal(47);
	}
} // /:~

 

你被强制在数据成员的定义处或者是每个构造器中用表达式对final进行赋值。这正是final数据成员在使用前总是被初始化的原因所在。

你可能感兴趣的:(J#,Access)