靜態(tài)數(shù)據(jù)初始化 你 真的了解了嗎?構(gòu)造方法的初始之后。。我又做錯(cuò)了,太粗心了
下面的程序輸出什么呢? 考慮下哦。。。。
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());
}
}
可能你覺得應(yīng)該是當(dāng)前年- 1930, 例如:今年是2009,2009-1930= 79,運(yùn)行結(jié)果真的是這樣嗎?
你運(yùn)行下,額,奇怪,居然是 -1930, 額,為什么呢??
原來 首先其靜態(tài)域 被設(shè)置為缺省值, TEST先設(shè)置為null, belt設(shè)置為0 , 然后TEST構(gòu)造器計(jì)算出來,但我們已經(jīng)初始化belt了,
belt被設(shè)置為final, 所以忽略了。。。
運(yùn)行結(jié)果: [1,2]:null















可能你覺得應(yīng)該是當(dāng)前年- 1930, 例如:今年是2009,2009-1930= 79,運(yùn)行結(jié)果真的是這樣嗎?
你運(yùn)行下,額,奇怪,居然是 -1930, 額,為什么呢??
原來 首先其靜態(tài)域 被設(shè)置為缺省值, TEST先設(shè)置為null, belt設(shè)置為0 , 然后TEST構(gòu)造器計(jì)算出來,但我們已經(jīng)初始化belt了,
belt被設(shè)置為final, 所以忽略了。。。
再來看下 下面一個(gè)簡(jiǎn)單的例子,剛開始做的時(shí)候不仔細(xì),哎,, 我錯(cuò)了。。哎~!~ 希望大家不要跟我一樣啊。
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 }
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 }
運(yùn)行結(jié)果: [1,2]:null
程序從main啟動(dòng),然后到 25行,super(x,y); 之后 到 第 8行 name = makeName(); 再之后29行, return super.makeName()+":"+color;
這里,方法被子類重載了,運(yùn)行到26行 this.color = color; 最后結(jié)束, 當(dāng)然輸出: [1,2]:null
這里,方法被子類重載了,運(yùn)行到26行 this.color = color; 最后結(jié)束, 當(dāng)然輸出: [1,2]:null
posted on 2009-04-15 19:28 胡鵬 閱讀(238) 評(píng)論(1) 編輯 收藏 所屬分類: java基礎(chǔ)