Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Pass by Reference constructor

Tags:

java

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
        }
}
like image 990
Saurav Jaiswal Avatar asked Jan 25 '23 14:01

Saurav Jaiswal


1 Answers

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;
}
like image 66
Eran Avatar answered Jan 28 '23 04:01

Eran