Java constructors assingning value to variable and then interchanging them

Hi

>Whats should be the output of the following code and why?
>the output turned out to be 131713.Below is the code. the object >references are interchanging so the values are changing.
enter code here

public class Test { int age; String name;

Test(int age,String name){
this.age=age;
this.name=name;

} public static void main(String[] args){

Test t1 = new Test(17,"A");
Test t2 = new Test(13,"B");
Test t3 = new Test(14,"C");
t3=t2;
t2=t1;
t1=t3;
System.out.print(t1.age);
System.out.print(t2.age);
System.out.print(t3.age);
}

}

Changing the value of a reference variable doesn't modify anything inside the object that it refers to. But it can make that variable refer to a different object. The variables exist independently of the objects. This can be visualised as in the following diagrams.

After you create your three objects, you have a situation like this.

      /               /               /       
      |       |        |       |        |       |
 t1-> | 17  A |   t2-> | 13  B |   t3-> | 14  C |     
      |       |        |       |        |       |
             /               /               /

Then you change what t3 refers to, so you have

      /               /               /       
      |       |   t2-> |       |        |       |
 t1-> | 17  A |        | 13  B |        | 14  C |     
      |       |   t3-> |       |        |       |
             /               /               /

Then you change what t2 refers to, so you have

      /               /               /       
 t1-> |       |        |       |        |       |
      | 17  A |   t3-> | 13  B |        | 14  C |     
 t2-> |       |        |       |        |       |
             /               /               /

And you change what t1 refers to, so you have

      /               /               /       
      |       |   t1-> |       |        |       |
 t2-> | 17  A |        | 13  B |        | 14  C |     
      |       |   t3-> |       |        |       |
             /               /               /

Then you start printing stuff. As shown in the final diagram above, t1.age and t3.age are both 13 , and t2.age is 17 .

链接地址: http://www.djcxy.com/p/66334.html

上一篇: 如何列出所有用户的所有cron作业?

下一篇: Java构造函数赋值给变量,然后交换它们