Java: Keyword final

With a primitive, final makes the value a constant. Once the reference is initialized to an object, it can never be changed to another object. However, the object itself can be modified. …… This restriction includes arrays, which are also objects.

 

public class Value {
    int i;

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

 

import java.util.Random;


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

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

    // Can be compile-time constructors.
    private final int valueOne = 9;
    private static final int VALUE_TWO = 99;
    //Typical public constant
    public static final int VALUE_THREE = 39;
    // Cannot be compile-time constants.   
    private final int i4 = rand.nextInt(20);
    static final int INT_5 = rand.nextInt(20);
    private Value v1 = new Value(11);
    private final Value v2 = new Value(22);
    private static final Value VAL_3 = new Value(33);
    // Arrrays
    private final int[] a = { 1, 2, 3, 4, 5, 6 };

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

   
    public static void main(String[] args) {
        FinalData fd1 = new FinalData("fd1");
        //        !fd1.valueOne++;   // Constant.
        fd1.v2.i++; // Object is not constant.
        fd1.v1 = new Value(9);
        for (int i = 0; i < fd1.a.length; i++) {
            fd1.a[i]++; // The reference is constant, but the content of it not.
        }
        //       ! fd1.v2 = new Value(0);     // Generally can't.
        //       ! fd1.VAL_3 = new Value(1);  // Reference is constant.
        //       ! 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);
    }
}

 

From 《Thinking in Java》 4th Edition .p263

你可能感兴趣的:(Java: Keyword final)