【发布时间】:2010-08-21 10:34:12
【问题描述】:
在学校我需要学习 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() 方法?)
【问题讨论】:
-
你的第一个输出正确吗?好像不是
-
报告的内容有问题。
-
这也是 Java 与 C++ 没有区别的一个领域。
-
您的代码已经运行。你应该澄清你的问题。
-
@Colin,我更新了我的代码,以向您展示代码所做的更多调用......这非常复杂(整个代码甚至更多:P)
标签: java inheritance constructor overriding