標籤:
1 import java.util.*; 2 3 class Value { 4 int i; 5 6 public Value(int i) { 7 this.i = i; 8 } 9 }10 11 public class FinalData {12 13 private static Random rand = new Random(47);14 private String id;15 16 public FinalData(String id) {17 this.id = id;18 }19 //can be compile-time constants:20 private final int valueOne = 9;21 private static final int VALUE_TWO = 99;22 //Typical public constant:23 public static final int VALUE_THREE = 39;24 //cannot be compile-time constants25 private final int i4 = rand.nextInt(20);26 static final int INT_5 = rand.nextInt(20);27 private Value v1 = new Value(11);28 private final Value v2 = new Value(22);29 private static final Value VAL_3 = new Value(33);30 private final int[] a = { 1, 2, 3, 4, 5, 6 };31 32 public String toString() {33 return id + ": i4 = " + i4 + ", INT_5 = " + INT_5;34 }35 36 public static void main(String[] args) {37 FinalData fd1 = new FinalData("fd1");38 //!fd1.valueOne++; //Error:cannot change value39 fd1.v2.i++;//Object is not constant40 fd1.v1 = new Value(9);//OK--not final41 for (int i = 0; i < fd1.a.length; i++) {42 fd1.a[i]++; //Object is not constant43 }44 //!fd1.v2=new Value(0); //Error:cannot45 //!fd1.VAL_3=new Value(1);//change reference46 //!fd1.a=new int[3];47 System.out.println(fd1);48 System.out.println("creating new FinalData");49 FinalData fd2 = new FinalData("fd2");50 System.out.println(fd1);51 System.out.println(fd2);52 }53 }
輸出
fd1: i4 = 15, INT_5 = 18creating new FinalDatafd1: i4 = 15, INT_5 = 18fd2: i4 = 13, INT_5 = 18
Java:The final Keyword