输出结果:
问题:第二行输出为i=10,所以为什么有参构造中x相当于i=10,
public class One {
private int i=1;
One x;
public One()
{
i=10;
x=null;
}
public One(int i)
{
this.i=i;
x=new One();
}
public void print()
{
System.out.println("i="+i);
System.out.println(x);
}
public String toString()
{
return "i="+i;
}
}
class Test{
public static void main(String args[]) {
One x=new One(100);
x.print();
System.out.println(x.x);
}
}
Java语言的构造函数要等到new构造的时候才会调用的。
【以下回答由 GPT 生成】
首先,让我们来看看你提供的代码,理解一下当前的问题所在。根据你的描述,我假设你的代码如下所示:
class One {
private int i;
public One() {
i = 0;
}
public One(int i) {
this.i = i;
One x = new One();
}
public void print() {
System.out.println("i=" + i);
}
public String toString() {
return "One[i=" + i + "]";
}
}
public class Test {
public static void main(String[] args) {
One x = new One(100);
x.print();
System.out.println("x.x: " + x.toString());
}
}
现在,让我们来解决你的问题。
问题的原因是,你在有参构造函数中创建了一个新的One对象,并将其赋值给变量x。然而,这个变量x只是在有参构造函数中的一个局部变量,并不是类的成员变量。所以,当你在main方法中调用x的print方法时,实际上是调用的类的成员变量x的print方法,而不是有参构造函数中的局部变量x的print方法。因此,输出结果为有参构造函数中的局部变量x的值,并不是你期望的值。
要解决这个问题,你需要将有参构造函数中创建的对象赋值给类的成员变量x,而不是局部变量x。你可以通过使用关键字"this"来引用类的成员变量。修改代码如下:
class One {
private int i;
private One x; // 在类的成员变量中声明x
public One() {
i = 0;
}
public One(int i) {
this.i = i;
this.x = new One(); // 使用"this"引用类的成员变量
}
public void print() {
System.out.println("i=" + i);
}
public String toString() {
return "One[i=" + i + "]";
}
}
public class Test {
public static void main(String[] args) {
One x = new One(100);
x.print();
System.out.println("x.x: " + x.toString());
}
}
运行修改后的代码,输出结果应该符合你的期望。希望这个回答对你有帮助。如果你还有任何问题,请随时问。
【相关推荐】