The alias mechanism in Java

Source: Internet
Author: User

Assigning an object to another object is actually copying the reference from one place to another. This means that if you use C=d for the object, then both C and D point to the object that was the only D point, and the following example illustrates this.

Package gao.com;class test{int number;} public class Assigment {public   static void Main (String[]args) {   Test t1=new test ();   Test t2=new test ();   t1.number=25;   t2.number=32;   System.out.println ("t1.number=" +t1.number+ "t2.number=" +t2.number);   T1=t2;   System.out.println ("t1.number=" +t1.number+ "t2.number=" +t2.number);   t1.number=1;   System.out.println ("t1.number=" +t1.number+ "t2.number=" +t2.number);}   } /* Output t1.number=25 t2.number=32t1.number=32 t2.number=32t1.number=1 t2.number=1*/

The Test class is very simple, and its two instances are created in main (). A different value is assigned to the Number field for each test class object. The T2 is then assigned to T1, and then the T1 is modified. In many languages we expect T1 and T2 to always be independent of each other, but because the assignment is a reference to an object, modifying T1 also changes T2, because T1 and T2 contain the same references, which point to the same object.

The alias mechanism in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.