Java中static,final和static final的區別

<!-- lang: java -->
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);
}

}java

運行結果爲:dom

<!-- lang: java -->
saft1.staticA: 58
saft1.finalB: 93
saft1.staticFinalC: 55
--------------------------------- 
saft1.staticA: 58
saft1.finalB: 61
saft1.staticFinalC: 55

這是由於它是static,在裝載時已被初始化,而不是每次建立新對象時都初始化。code

相關文章
相關標籤/搜索