編程生活

             :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            113 隨筆 :: 0 文章 :: 18 評論 :: 0 Trackbacks

          如下代碼會出問題
          public class C {
              private String c1;

              private String c2;

              public void setC1(String c1) {
                  this.c1 = c1;
              }

             public String getC1() {
                  return this.c1;
              }

              public void setC2(String c2) {
                  this.c2 = c2;
              }

             public String getC2() {
                  return this.c2;
              }
          }

          public abstract class A extends Composite {
              public A(Composite parent, int style) {
                  super(parent, style);
                  createMainBody(parent);
                  createOtherBox();
              }
              
              protected abstract void createMainBody(Composite parent);
              protected abstract void createOtherBox(Composite parent);
          }

          public class B extends A{
              private Text b1 = null; //VE生成的
              ...
              private C c = new C();

              public B(Composite parent, int style) {
                  super(parent, style);
              }
              
              protected void createMainBody(Composite parent) {
                  b1 = new Text(parent, SWT.NONE);
                  b1.addModifyListener(new ModifyListener() {
                      public void modifyText(ModifyEvent e) {
                          c.setC1(b1.getText());
                          fireFormDataChange();
                      }
                  });
                  b1.setText("Hello...");
                  ...
              }
              ...
          }
          一運行代碼出錯了,經過調試才發現B初始化時,在super(..)執行完之前并沒有初始化本類(這是對的),自己的代碼實現有問題.
          注意:類初始化時,首先初始化父類,再初始化本類的變量聲明部分,初始化父類時如果回調到子類的某些類的實現,而這些實現方法又完成了對聲明變量的創建,再回來初始化本類時,如果聲明變量有初始值,又會將這些變量設置到初始值狀態,因此,會發現這些變量無法訪問了.一切都是對的,只是自己太相信VE生成的代碼了.
          改動很簡單,只是將
          public class B extend   A { 
              private Text b1;    
              ...
              private C c;

              public B(Composite parent, int style) {
                  super(parent, style);
              }
              
              protected void createMainBody(Composite parent) {
                  c = new C();
                  ...
              }
          }
          好,這樣就一切OK.類的初始化過程的學習還是很重要的.

          posted on 2007-11-06 09:09 wilesun 閱讀(644) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 定州市| 芮城县| 靖远县| 碌曲县| 大埔区| 宣汉县| 西平县| 博客| 京山县| 清徐县| 大姚县| 大冶市| 扶风县| 静乐县| 宜丰县| 许昌市| 囊谦县| 阿克苏市| 常熟市| 桐城市| 开封市| 马关县| 开阳县| 灵山县| 马山县| 尉氏县| 二手房| 叶城县| 黔江区| 浙江省| 杂多县| 兰考县| 平山县| 岐山县| 乐陵市| 罗平县| 湟源县| 连云港市| 凤凰县| 长顺县| 海晏县|