May 21
有繼承和沒繼承StaticSuper,以下兩者有微妙的不同。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | class StaticSuper { static { System.out.println("super static block"); } StaticSuper(){ System.out.println("super constructor"); } } public class StaticTest extends StaticSuper { // { static int rand; static { rand = (int) (Math.random()*6); System.out.println("static block " + rand); } StaticTest(){ System.out.println("constructor"); } public static void main(String[] args) { System.out.println("in main"); StaticTest st = new StaticTest(); } } |
result:
super static block
static block 5
in main
super constructor
constructor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class StaticSuper { static { System.out.println("super static block"); } StaticSuper(){ System.out.println("super constructor"); } } public class StaticTest { //註解掉 extends StaticSuper static int rand; static { rand = (int) (Math.random()*6); System.out.println("static block " + rand); } StaticTest(){ System.out.println("constructor"); } public static void main(String[] args) { System.out.println("in main"); StaticTest st = new StaticTest(); } } |
result:
static block 1
in main
constructor
ref: Head First Java 第十章練習題
溫故知新
載入中…
歷史上的今天..
- 酷!在終端機以 ASCII 來觀賞影片 - 2007







最新回應