简单来看,static final 跟 final 的区别就是前者多了个static。static表示是静态的,static含有两个很关键的特点。一是static分配的存储空间不会变,而且static会在装载的时候初始化,而不是每次创建新对象时都初始化。二是static修饰的属性或方法又叫类属性或类方法,也就说可以直接通过类名进行调用。只要把握住这两个关键点,问题就不大了,通过一个实例来看看区别:
/* Create a class with a static final field and a final field and demonstrate
* the difference between the two.
*/
import java.util.*;
class Test {
Test(int i) {
System.out.println("Test("+ i +")");
}
}
public class Difference {
private String name;
public Difference(String s) { name = s; }
static final Test sft = new Test(1); // constant reference address
private final Test ft = new Test(2);
static final String SFS = "static final"; // class constant
private final String fs = "final";
private static Random rand = new Random();
static final int SFI = rand.nextInt(); // class constant
private final int fi = rand.nextInt();
public String toString() {
return (name + ": " + sft + ", " + ft + ", " + SFS + ", " + fs + ", " + SFI + ", " + fi);
}
public static void main(String[] args) {
Difference d1 = new Difference("d1");
Difference d2 = new Difference("d2");
Difference d3 = new Difference("d3");
System.out.println(d1);
System.out.println(d2);
System.out.println(d3);
}
}
/* Output:
* Test(1)
* Test(2)
* Test(2)
* Test(2)
* d1: Test@5e8fce95, Test@3343c8b3, static final, final, 1548590506, 392950174
* d2: Test@5e8fce95, Test@272d7a10, static final, final, 1548590506, 1631623563
* d3: Test@5e8fce95, Test@1aa8c488, static final, final, 1548590506, 1178201149
*/
说明:sft是static的,所以只被初始化一次,而ft被初始化了三次。SFI的值是不会在第二次创建对象时发生改变的,因为它是static的,在装载时已被初始化,而不是每次创建新对象时都初始化。直接使用类名来调用类属性或类方法没有在这演示。