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. It returned me 0 0
instead of 40, 4
as an 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.
Perhaps you intended to write:
Test(Test ob) {
this.a = ob.a*2;
this.b = 2*2;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With