Thinking in Java(8)-final keyword

1.final data
The following example shows the basic rules of final keyword:

import java.util.*;

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


public class FinalData {
    private static final Random rand = new Random();
    private String id;
    public FinalData(String id) {
        this.id = id;
    }
    private final int valueOne = 9;
    private static final int VALUE_TWO = 99;
    public static final int VALUE_THREE = 39;
    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);
    //Arrays
    private final int[] a = {1,2,3,4,5,6};
    public String toString() {
        return id + ": " + "i4 = " + i4 + ", INT_5 = " + INT_5;
    }

    public static void main(String[] args) {
        FinalData fd1 = new FinalData("fd1");
        //!fd1.valueOne++; //Error! Can't change final value
        fd1.v2.i++;//Object isn't constant!
        fd1.v1 = new Value(9);
        for (int i = 0;i < fd1.a.length;i++)
        {
            fd1.a[i]++;//Object isn't constant
        }
        //!fd1.v2 = new Value(2);
        //!fd1.VAL_3 = new Value(1);
        //!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);

    }

}

result:

fd1: i4 = 1, INT_5 = 7
Creating new FinalData
fd1: i4 = 1, INT_5 = 7
fd2: i4 = 14, INT_5 = 7

i4 changed,but INT_5 wasn’t.This shows static final data is initialized once upon loading and not each time a new object is created.

2.Blank final provide much more flexibility in the use final keyword,for example,a final field inside a class can be different for each object,and yet retains its immutable qualities.

3.final arguments
When the argument list is declared as final,you can’t change what the argument reference points to.

4.final methods
In recent versions if Java,you can make a method **final**only if you want to explicitly prevent overriding.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值