Rocky Snail(小蝸牛)

          一步一步往上爬、小小的天、大大的夢(mèng)想、 強(qiáng)健體魄、充實(shí)頭腦

           

          寫構(gòu)造函數(shù)時(shí)應(yīng)該注意的

          撰寫構(gòu)造函數(shù)時(shí),“盡可能簡(jiǎn)單的讓對(duì)象進(jìn)入正確狀態(tài)。如果可以的話別調(diào)用任何函數(shù)”,構(gòu)造函數(shù)中唯一可以安全調(diào)用的函數(shù)時(shí)“base class中的final函數(shù)和private函數(shù)”,這樣的函數(shù)無(wú)法被重寫。
          原因:看下列程序。
               abstract class Glyph {
                      abstract void draw();
                    Glyph(){
                       System.out.println("Glyph() before draw()");
                       draw();  //注意這個(gè)函數(shù),他的調(diào)用順序
                       System.out.println("Glyph after draw()");
                   }
           
          }
           
          class RoundGlyph extends Glyph{
               int radius =  1;
               RoundGlyph(int r) {
                 radius = r;
                 System.out.println{
                  "ToundGlyph.ToundGlyph(),radius = " + radius);
                }
               void draw(){
                 System.out.println("RoundGlyph.draw(), radius = " + radius);
               }
          }


           public class PolyConstructors{
                  public static void main(String args[]){
                      new RoundGlyph(5);
                  }
          }
          輸出的結(jié)果是:Glyph() before draw()
                                      RoundGlyph.draw(), radius = 0
                                       Glyph() after draw()
                                       RoundGlyph.RoundGlyph(),  radius = 5
          我們看到在超類的構(gòu)造函數(shù)中調(diào)用了一個(gè)抽象函數(shù)Draw(),這時(shí)radius尚未被初始化為1,所以其值為0。構(gòu)造函數(shù)中不會(huì)為某個(gè)調(diào)用函數(shù)進(jìn)行解析動(dòng)態(tài)綁定,找出它隸屬的class,他的任務(wù)是對(duì)象從無(wú)到有,他最終調(diào)用的這個(gè)函數(shù)是位于他最終被覆寫的那個(gè),而此時(shí)那個(gè)類還沒有完全初始化,這會(huì)造成災(zāi)難性的后果。(出自JAVA編程思想 P239)。

          posted on 2006-03-13 11:50 Rockysnail 閱讀(330) 評(píng)論(0)  編輯  收藏 所屬分類: Java

          導(dǎo)航

          統(tǒng)計(jì)

          常用鏈接

          留言簿(1)

          隨筆分類

          隨筆檔案

          搜索

          最新評(píng)論

          閱讀排行榜

          評(píng)論排行榜

          主站蜘蛛池模板: 桂东县| 昭平县| 博罗县| 环江| 稻城县| 和林格尔县| 崇文区| 漠河县| 客服| 张掖市| 渝中区| 临汾市| 富源县| 精河县| 兴山县| 达日县| 靖安县| 招远市| 沙田区| 双辽市| 修水县| 沂南县| 凯里市| 石门县| 花莲县| 共和县| 陇西县| 华宁县| 麻城市| 福安市| 博客| 南丰县| 定兴县| 岚皋县| 凤山县| 互助| 无棣县| 玛纳斯县| 萍乡市| 阆中市| 宝山区|