Class的成员变量的初始化问题

Class的成员变量的初始化问题

如下代码会出问题
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.类的初始化过程的学习还是很重要的.

你可能感兴趣的:(Class的成员变量的初始化问题)