首先,老生常谈一下概念。

一直以来,林檀都是这样记的:
被final修饰的变量叫做常量。
被static final修饰的变量叫做静态常量。

直到前段时间,林檀在复习Java基础时,从SF上看到这样一篇问答:
https://segmentfault.com/q/1010000008424271

其中提到:
Java语言规范中有final Variables的和constants概念。
只用final修饰的变量应该就叫做最终变量。
static和final同时修饰才被称之为常量。

static variables that are final and that are initialized with compile-time constant values are initialized first. This also applies to such fields in interfaces (§9.3.1). These variables are “constants”

好吧,毕竟是官方给出的语言规范,可信度Max。
拿出小本本,姑且记下。

最后,加深一下印象,做一个小栗子好了。

import java.util.Random;

//源址: https://www.cnblogs.com/dingruihfut/p/9096226.html
public class StaticAndFinalTest {
    private static Random rand = new Random(47);//47作为随机种子,为的就是产生随机数
    private final int mIntA = rand.nextInt(20);
    private static final int mIntB = rand.nextInt(20);

    public static void main(String[] args) {
        StaticAndFinalTest sf01 = new StaticAndFinalTest();
        System.out.println("sf01: " + "mIntA=" + sf01.mIntA);
        System.out.println("sf01: " + "mIntB=" + sf01.mIntB);

        StaticAndFinalTest sf02 = new StaticAndFinalTest();
        System.out.println("sf02: " + "mIntA=" + sf02.mIntA);
        System.out.println("sf02: " + "mIntB=" + sf02.mIntB);
    }
}

输出结果:

sf01: mIntA=15
sf01: mIntB=18

sf02: mIntA=13
sf02: mIntB=18

可以看到,在sf01和sf02对象中,mIntA的值不唯一,mIntB的值唯一。

分类: PL_Java

0 条评论

发表回复

Avatar placeholder

您的电子邮箱地址不会被公开。