當(dāng)一個(gè)類中有聲明為static final的變量,這樣的變量對(duì)類的加載器有一定的影響,首先看看下面的例子。
- package com.bird.classLoad;
-
- class FinalTest{
-
- public static final int a = 6/3;
-
- static{
- System.out.println("FinalTest static block");
- }
- }
-
- public class Test3 {
- public static void main(String[] args) {
- System.out.println(FinalTest.a);
- }
- }
因?yàn)閍是static final變量,且它等于6/3,在編譯的時(shí)候就可以知道它的值,所以直接訪問a的值不會(huì)引起FinalTest類的初始化。作為表現(xiàn),也就是static靜態(tài)代碼快不會(huì)被加載。
運(yùn)行結(jié)果為
- 2
在看一個(gè)例子
- package com.bird.classLoad;
-
- import java.util.Random;
-
- class FinalTest4{
-
- public static final int a = new Random().nextInt(100);
-
- static{
- System.out.println("FinalTest4 static block");
- }
- }
-
- public class Test4 {
-
- public static void main(String[] args) {
- System.out.println(FinalTest4.a);
- }
- }
這個(gè)static final變量a因?yàn)閕在編譯的時(shí)候無法知道它的確切的值,所以只有等到運(yùn)行的時(shí)候才能知道,所以自己訪問FinalTest4.a會(huì)引起FinalTest4類的初始化。也就是static靜態(tài)代碼快的加載。
運(yùn)行結(jié)果為
- FinalTest4 static block
- 82
下面的例子是講,當(dāng)子類被主動(dòng)訪問的時(shí)候,會(huì)引起其直接父類的初始化
- package com.bird.classLoad;
-
- class Parent{
-
- static int a = 3;
-
- static{
- System.out.println("Parent static block");
- }
- }
-
- class Child extends Parent{
-
- static int b = 4;
- static{
- System.out.println("Chind static block");
- }
- }
-
- public class Test5 {
-
- public static void main(String[] args) {
- System.out.println(Child.b);
-
- }
- }
因?yàn)橹苯釉L問Child,b,會(huì)先初始化Parent類,然后初始化Child類。
運(yùn)行結(jié)果為
- Parent static block
- Chind static block
- 4
如果通過子類直接訪問父類的變量,只會(huì)初始化父類而不會(huì)初始化子類
- package com.bird.classLoad;
-
- class Parent{
-
- static int a = 3;
-
- static{
- System.out.println("Parent static block");
- }
- }
-
- class Child extends Parent{
-
- static{
- System.out.println("Chind static block");
- }
- }
-
- public class Test5 {
-
- public static void main(String[] args) {
- System.out.println(Child.a);
-
- }
- }
直接訪問Parent類的a變量,則只會(huì)直接初始化parent類,不會(huì)初始化Child類
運(yùn)行結(jié)果如下
- Parent static block
- 3