[英]Java Pass by Reference constructor
I created two objects for the test class where I passed the values 10 and 20
and when I passed second object to the test constructor.我为测试 class 创建了两个对象,其中我传递了值
10 and 20
,当我将第二个 object 传递给测试构造函数时。 It returned me 0 0
instead of 40, 4
as an output.它返回我
0 0
而不是40, 4
作为 output。 Can anyone explain me why is it happening so?谁能解释我为什么会这样?
class Test{
public int a,b;
Test(){
a=-1;
b=-1;
}
Test(int i,int j){
a=i;
b=j;
}
void mest(Test o){
o.a*=2;
o.b=2*2;
}
Test(Test ob){
ob.a*=2;
ob.b=2*2;
}
}
public class Main{
public static void main(String[] args){
Test t = new Test(10,20);
System.out.println(t.a +" "+ t.b);// 10, 20
t.mest(t);
System.out.println(t.a +" "+ t.b);// 20, 4
Test t2 = new Test(t);
System.out.println(t2.a +" "+ t2.b); // 0 , 0
}
}
Your Test(Test ob)
constructor mutates the instance variables of the instance you pass to it ( Test ob
), leaving the properties of the newly created instance with default 0
values.您的
Test(Test ob)
构造函数会改变您传递给它的实例的实例变量( Test ob
),使新创建的实例的属性具有默认值0
。
Perhaps you intended to write:也许你打算写:
Test(Test ob) {
this.a = ob.a*2;
this.b = 2*2;
}
You change the variables of ob
instead of assigning them to this.a
and this.b
.您更改
ob
的变量,而不是将它们分配给this.a
和this.b
。
You probably want to use this:你可能想用这个:
Test(Test ob){
this.a = ob.a*2;
this.b = 4;
}
You are seeing 0's because the default value of primitive data types is either 0
or false
in the case of boolean
.您看到的是 0,因为在
boolean
的情况下,原始数据类型的默认值为0
或false
。
Edit: In any case you shouldn't alter any variables in a copy constructor except for just copying.编辑:在任何情况下,除了复制之外,您不应更改复制构造函数中的任何变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.