用Java重写构造函数

时间:2010-08-21 10:34:13

标签: java inheritance constructor override

对于学校我需要学习Java,因为我习惯使用基于C ++(如Cocoa / Objective-C)的语言,所以我对Java感到非常沮丧。

我做了一个超类(也可以用作基类):

public class CellView {
    public CellViewHelper helper; // CellViewHelper is just an example

    public CellView() {
        this.helper = new CellViewHelper();
        this.helper.someVariable = <anything>;

        System.out.println("CellView_constructor");
    }

    public void draw() {
        System.out.println("CellView_draw");
    }

    public void needsRedraw() {
        this.draw();
    }

}

public class ImageCellView extends CellView {

    public Image someImage;

    public ImageCellView() {
        super();
        this.someImage = new Image();
        System.out.println("ImageCellView_constructor");
    }

    public void setSomeParam() {
        this.needsRedraw(); // cannot be replaced by this.draw(); since it's some more complicated.
    }

    @Override public void draw() {
        super.draw();
        System.out.println("ImageCellView_draw");
    }

}

现在,当我这样称呼时:

ImageCellView imageCellView = new ImageCellView();
imageCellView.setSomeParam();

我明白了:

  

CellView_constructor

     

ImageCellView_constructor

     

CellView_draw

但是,我希望它是:

  

CellView_constructor

     

ImageCellView_constructor

     

CellView_draw

     

ImageCellView_draw

我该怎么做?

提前致谢,

修改

我还将此方法实现到CellView:

public void needsRedraw() {
    this.draw();
}

这是ImageCellView:

public void setSomeParam() {
    this.needsRedraw(); // cannot be replaced by this.draw(); since it's some more complicated.
}

我一直在说这个:

ImageCellView imageCellView = new ImageCellView();
imageCellView.setSomeParam();

这是否会导致问题(当我从super调用一个函数时,它只调用super )?我怎样才能解决这个问题...(无需在每个子类中重新定义/覆盖needsRedraw() - 方法?)

2 个答案:

答案 0 :(得分:2)

你应该得到适当的输出。

我试过你的例子只评论了无关的事情:

import java.awt.Image;

public class CellView {
    //public CellViewHelper helper; // CellViewHelper is just an example

    public CellView() {
        //this.helper = new CellViewHelper();
        //this.helper.someVariable = <anything>;

        System.out.println("CellView_constructor");
    }

    public void draw() {
        System.out.println("CellView_draw");
    }

    public static void main(String[] args) {
        ImageCellView imageCellView = new ImageCellView();
        imageCellView.draw();
    }
}

class ImageCellView extends CellView {

    public Image someImage;

    public ImageCellView() {
        super();
        //this.someImage = new Image();
        System.out.println("ImageCellView_constructor");
    }

    @Override public void draw() {
        super.draw();
        System.out.println("ImageCellView_draw");
    }

}

我得到以下输出:

  

CellView_constructor

     

ImageCellView_constructor

     

CellView_draw

     

ImageCellView_draw

这正是您想要的,这就是您的代码打印的内容。

答案 1 :(得分:1)

简短的回答是“你做不到”。

对象从下到上构造,在子类初始化器之前调用基类初始化器,在子类构造器之前调用基类构造器。

编辑:

根据您的编辑,您所拥有的代码看起来不错。我会完成一些平凡的任务,例如确保在将System.out.println调用添加到子类之后编译代码