C a2 = new C();
C a1 = new C();
C a3 = new C();
a1.i = a3.i; // => a3.i = 0 then a1.i = 0;
a2 = a1; // => a1 and a2 are the same objects (point to the same references)
a2.i = 12; //=> a2.i = 12, so a1.i = 12
a3.i = a3.i + 1;// => a3.i = 1
a1.i = 9; // => a1.i = 9 so a2.i = 9
a1.k = 11; // => a1.k = 11 so a2.k = 11
a2.k = 12; // => a2.k = 12 so a1.k = 12
//a1.i = 9 / a2.i = 9 / a3.i = 1 / a1.k = 12 / a2.k = 12
System.out.println(a1.i + " " + a2.i + " " + a3.i + " " + a1.k + " " + a2.k);
Can someone please explain object referencing in Java? [closed]
-
01-07-2022 - |
سؤال
The output i get is 9 12 1 11 12 however it should be 9 9 1 12 12. I know it has something to do with a2 = a1; but can't see how .
public class C {
/**
* @param args the command line arguments
*/
private int i;
private int k = 10;
public static void main(String[] args) {
// TODO code application logic here
C a2 = new C();
C a1 = new C();
C a3 = new C();
a1.i = a3.i;
a2 = a1;
a2.i = 12;
a3.i = a3.i + 1;
a1.i = 9;
a1.k = 11;
a2.k = 12;
System.out.println(a1.i + " " + a2.i + " " + a3.i + " " + a1.k + " " + a2.k);
}
}
المحلول
نصائح أخرى
This code: a2=a1
means that reference a2
will point to the same object as a1
.
Therefore, you have 2 references that point to the same object. When the object changes, if you use either reference, you will get the same value.
Also. by running your program i get the correct value: 9 9 1 12 12
.
Maybe some comments will help you to understand what's going on:
a1.i = a3.i; // a3.i = 0 = a1.i
a2 = a1; // now the old object a2 is lost and a2 points to a1
a2.i = 12; // a2.i = 12 = a1.i
a3.i = a3.i + 1; // a3.1 = 0 + 1
a1.i = 9; // a1.i = 9 = a2.i
a1.k = 11; // a1.k = 11 = a2.k
a2.k = 12; // a2.k = 12 = a1.k
At the end of the execution we have:
a1.i = 9
a2.i = 9
a3.i = 1
a1.k = 12
a2.k = 12
لا تنتمي إلى StackOverflow