![](/img/trans.png)
[英]In BlueJ, how do I correctly call variables created in one constructor to a constructor in another class?
[英]How do I call the no arg constructor after I have allready created an object of the class?
我创建该类的对象:
Rectangle rec = new Rectangle(2,4);
这给出了我的矩形和2的高度和4的宽度。
但是无论如何,以后我可以在代码中调用no arg构造函数而不创建新对象吗?
不这样做:
Rectangle rec2 = new Rectangle();
通常,这是一个信号,您需要重构构造函数,以便将两个或多个构造函数公用的所有代码包含在单独的(非构造函数)方法中。
构造函数根据其定义创建新对象。
如果不再需要rec
,则可以执行rec = new Rectangle()
前提是Rectangle没有arg构造函数。
还是只想替换当前矩形的值? 如果是这样,只需通过设置器进行更改,以创建一种方法来更新两个值...
你不能。 您可以使用反射来创建新对象,而无需使用new关键字,但是我不确定它是否调用构造函数。
您可以在方法中设置对象的基本属性,然后在构造函数中调用该方法
要么
在您的情况下,使用rec = null; rec = new Rectangle(); //如果您不需要Rectangle(2,4)
不,您只能调用一个构造函数。
如果要覆盖坐标,可以使用setBounds
方法,例如
rec.setBounds(0,0,0,0);
但是,除非您要开发手机游戏,否则重新使用旧矩形没有什么意义,创建新矩形更简单。
您绝对可以,这是如何
public class Example {
//no arg constructor
public Example() {
//your code
}
//constructor with argument
public Example(String arg) {
//call the no arg constructor
this();
//do something else
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.