4

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
        }
}
  • 1
    [You can't pass by reference in Java](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value). You're passing an object reference by value, which isn't the same. – jsheeran Nov 21 '19 at 11:08
  • I don't understand why you expect the results to be anything else. Can you explain? – DodgyCodeException Nov 21 '19 at 11:12

2 Answers2

5

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;
}
Eran
  • 387,369
  • 54
  • 702
  • 768
3

You change the variables of ob instead of assigning them to this.a and 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.

Edit: In any case you shouldn't alter any variables in a copy constructor except for just copying.

Raildex
  • 3,406
  • 1
  • 18
  • 42