我为测试类创建了两个对象,在那里我传递了值10 and 20,当我将第二个对象传递给测试构造函数时。它返回我0 0而不是40, 4作为输出。谁能解释我为什么会这样?
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
}
}
Run Code Online (Sandbox Code Playgroud)
您的Test(Test ob)构造函数会改变您传递给它的实例的实例变量 ( Test ob),将新创建的实例的属性保留为默认0值。
也许你打算写:
Test(Test ob) {
this.a = ob.a*2;
this.b = 2*2;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
114 次 |
| 最近记录: |