Hello! Help me understand a simple example:

public class Test16 { public static void main(String[] args) { Qwe q1 = new Qwe(); Qwe q2 = q1; q1.q = 1; for (int i = 0; i < 2; i++) { q2.q = q2.q + q1.q; System.out.println(q2.q); System.out.println(q1.q); } } public static class Qwe { int q = 0; } } Вывод будет такой: 2 2 //Вопрос, почему увеличивается переменная q экземпляра класса q1, когда она должна быть всегда = 1? 4 4 

Apparently I do not understand this line Qwe q2 = q1; What's going on here? If instead write Qwe q2 = new Qwe(); then the output will be:

 1 1 // это понятно 2 1 
  • 3
    Qwe q2 = q1; - You declare a q2 variable that refers to the same object as q1 . - Nofate
  • I understand this, but why does q1.q change in a loop? - Igor
  • It came at last! Thank! - Igor

1 answer 1

Qwe q2 = q1; Here you assign q2 a reference to the class q1. The conclusion is absolutely correct and in one case. In the first, it is correct, because in q2 we have a reference to q1, which means that all the values ​​of the variables were also transferred to q2. in your cycle, q2 is 1 , and then you add 0 = 1 + 1 to this value;

If you assign Qwe q2 = new Qwe(); then the q value will be equal to not one, but 0. And according to this other conclusion.

When you pass a class reference to another class, Qwe q2 = q1; you also pass all the variable values ​​to the class, and since q1.q was assigned 1 , in q2, the variable q is also equal to one.

  • It still does not reach, let me write as I think, and you will correct me :) q1.q = 1 Iteration 1: q2.q = 1 (since q2 refers to q1) + 1 = 2 but q1.q = should be equal 1, why did he become 2? Iteration 2: q2. q = 2 + 1 = 3 Again, if it dawned on me why q1.q changes then q2.q would be understandable. Hence the question why q1.q changes? )) I understand that I do not understand the simple. Although in theory everything is clear. - Igor
  • @Ihor since two classes refer to one area in memory and if the q2 parameter in the class has changed, then it will also change in the class of q1 without full-time assignment to it. - raviga
  • @Igor q2 and q1 is the same object. Change q2 - change q1. - Nofate
  • Thank!! Now I get it! - Igor