下面的程序輸出什么呢? 考慮下哦。。。。

public class Test
{
public static final Test TEST = new Test();
private final int belt;
private static final int CURRENT_YEAR = Calendar.getInstance().get(Calendar.YEAR);

public Test()
{
belt = CURRENT_YEAR - 1930;
}

public int getBelt()
{
return belt;
}

public static void main(String []args) throws Exception
{
System.out.println(TEST.getBelt());
}
}
可能你覺得應該是當前年- 1930, 例如:今年是2009,2009-1930= 79,運行結果真的是這樣嗎?
你運行下,額,奇怪,居然是 -1930, 額,為什么呢??
原來 首先其靜態域 被設置為缺省值, TEST先設置為null, belt設置為0 , 然后TEST構造器計算出來,但我們已經初始化belt了,
belt被設置為final, 所以忽略了。。。
再來看下 下面一個簡單的例子,剛開始做的時候不仔細,哎,, 我錯了。。哎~!~ 希望大家不要跟我一樣啊。
1 class Point {
2 protected final int x, y;
3 private final String name;
4
5 Point(int x, int y) {
6 this.x = x;
7 this.y = y;
8 name = makeName();
9 }
10
11 protected String makeName() {
12 return "[" + x + "," + y + "]";
13 }
14
15 public final String toString(){
16 return name;
17 }
18
19 }
20
21 public class ColorPoint extends Point {
22 private final String color;
23
24 ColorPoint(int x, int y, String color){
25 super(x,y);
26 this.color = color;
27 }
28 protected String makeName() {
29 return super.makeName()+":"+color;
30 }
31
32 public static void main(String[] args) {
33 System.out.println(new ColorPoint(1,2,"abc"));
34 }
35
36 }
運行結果: [1,2]:null
程序從main啟動,然后到 25行,super(x,y); 之后 到 第 8行 name = makeName(); 再之后29行, return super.makeName()+":"+color;
這里,方法被子類重載了,運行到26行 this.color = color; 最后結束, 當然輸出: [1,2]:null