gpt4 book ai didi

java - 重写 Java 中的构造函数

转载 作者:行者123 更新时间:2023-12-02 00:50:12 26 4
gpt4 key购买 nike

在学校,我需要学习 Java,而且由于我习惯了基于 C++(如 Cocoa/Objective-C)的语言,所以我对 Java 感到非常沮丧。

我创建了一个父类(super class)(也可以用作基类):

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 )?我怎样才能解决这个问题...(不必在每个子类中重新定义/覆盖 needRedraw() 方法?)

最佳答案

您应该得到正确的输出。

我试过你的例子只是评论了不相关的事情:

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

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

关于java - 重写 Java 中的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3537277/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com