gpt4 book ai didi

Java : can't call overloaded constructor

转载 作者:行者123 更新时间:2023-11-30 07:24:56 25 4
gpt4 key购买 nike

在这里,我试图在我的 main() 程序中满足某些条件后调用重载的构造函数,该条件由变量 a 给出。当我只使用默认构造函数时,代码工作正常,但我需要在某些时候调用重载的构造函数,但它失败了。以下是代码:

重载构造函数:

public Paddle(int a){

if(a ==1){
ImageIcon ii = new ImageIcon(this.getClass().getResource(paddle1));
image = ii.getImage();
}
else {
ImageIcon ii = new ImageIcon(this.getClass().getResource(paddle2));
image = ii.getImage();
}
width = image.getWidth(null);
height = image.getHeight(null);
resetState();
}

// further initialization --

默认构造函数:

 public Paddle(){

ImageIcon ii = new ImageIcon(this.getClass().getResource(paddle));
image = ii.getImage();

width = image.getWidth(null);
height = image.getHeight(null);
System.out.println(height+" "+width);
resetState();
}

提前感谢您的帮助,可以提出进一步的疑问,但我认为这段代码有一些问题。谢谢

最佳答案

回答

您没有在重载的构造函数中设置实例变量 image

正确的方式

你这样做的方式违反了DRY (不要重复自己)!

最好的方法是让 no arg 构造函数调用重载的构造函数,然后在一个地方设置实例变量 image

public Paddle(final int i) 
{
if (i==1) { this.image = one thing }
else
{ this.image = another thing }
}

public Paddle() { this(0); }

更好的方法是将资源传递给单个构造函数并完成它,而不看所有代码,这看起来过于复杂。

关于Java : can't call overloaded constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11196861/

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