final

Different Kinds of Variables:
例子:

class Point {
    static int numPoints;   // numPoints is a class variable
    int x, y;               // x and y are instance variables
    int[] w = new int[10];  // w[0] is an array component
    int setX(int x) {       // x is a method parameter
        int oldx = this.x;  // oldx is a local variable
        this.x = x;
        return oldx;
    }
}

final Variables
A variable declared final . A final variable may only be assigned to once. Declaring a variable final can serve as useful documentation that its value will not change and can help avoid programming errors.
final修饰的变量只能被assign一次,即它的值不可以改变。

Once a final variable has been assigned, it always contains the same value. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.
final 变量一旦被赋值,其值就不可以改变,而如果一个final变量保存的是一个对象的引用,那么这个对象状态可以改变,但变量一直引用同一个对象。

This applies also to arrays, because arrays are objects; if a final variable holds a reference to an array, then the components of the array may be changed by operations on the array, but the variable will always refer to the same array.

这也适用数组,因为数组是对象。如果final 变量是一个数组的引用,那个数组元素可以改变,但是这个变量始终引用相同的数组。

例如,下面这段代码:

    //local inner class
    void getValue() {
        // Note that local variable(sum) must be final till JDK 7
        // hence this code will work only in JDK 8
     final   int sum = 20;


        class Inner {
            public int divisor;
            public int remainder;

            public Inner() {
               sum=25
                divisor = 4;
                remainder = sum % divisor;
            }

            public int getDivisor() {
                return divisor;
            }

            public void setDivisor(int divisor) {
                this.divisor = divisor;
            }

            public int getRemainder() {
                return remainder;
            }

            public void setRemainder(int remainder) {
                this.remainder = remainder;
            }

            private int getQuotient() {
                System.out.println("Inside inner class");
                return sum / divisor;
            }
        }

        Inner inner = new Inner();

        System.out.println("Divisor = " + inner.getDivisor());
        System.out.println("Remainder = " + inner.getRemainder());
        System.out.println("Quotient = " + inner.getQuotient());
        System.out.println(" local access enclosing private= " + outer_private);

        System.out.println(" local access enclosing x= " + outer_x);
        System.out.println(" local access enclosing y= " + outer_y);
    }

sum =25 会报错:can not assign a value to a final variable
因为是final 变量,所以不可以仔赋值了!!!

你可能感兴趣的:(final)