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
Qwe q2 = q1;- You declare aq2variable that refers to the same object asq1. - Nofate ♦