Java中static,final和static final的区别


package com.victor.test;
import java.util.Random;
public class StaticAndFinalTest {
private static Random rand = new Random(47);
private static int staticA = rand.nextInt(100);
private final int finalB = rand.nextInt(100);
private static final int staticFinalC = rand.nextInt(100);
public static void main(String[] args) {
    StaticAndFinalTest saft1 = new StaticAndFinalTest();
    System.err.println("saft1.staticA: " + saft1.staticA);
    System.err.println("saft1.finalB: " + saft1.finalB);
    System.err.println("saft1.staticFinalC: " + saft1.staticFinalC);
    System.err.println("---------------------------------");
    StaticAndFinalTest saft2 = new StaticAndFinalTest();
    System.err.println("saft1.staticA: " + saft2.staticA);
    System.err.println("saft1.finalB: " + saft2.finalB);
    System.err.println("saft1.staticFinalC: " + saft2.staticFinalC);
}

}

运行结果为:


saft1.staticA: 58
saft1.finalB: 93
saft1.staticFinalC: 55
--------------------------------- 
saft1.staticA: 58
saft1.finalB: 61
saft1.staticFinalC: 55

这是因为它是static,在装载时已被初始化,而不是每次创建新对象时都初始化。

你可能感兴趣的:(Java中static,final和static final的区别)