11.11 SEMANTICS OF THE ASSIGNMENT OPERATOR IN JAVA


11.11 SEMANTICS OF THE ASSIGNMENT OPERATOR IN JAVA

Since there are no pointers in Java—at least not in the same sense as in C++—there is no need to specify the copy constructors and copy assignment operators now. However, that does not mean that a simple assignment, whether for initialization or otherwise, has what intuition would ascribe to it at first thought. Consider the following code:

 
//AssignTest.java class User { public String name; public int age; public User( String str, int n ) { name = str; age = n; } } class Test { public static void main(String[] args) { User u1 = new User("ariel", 112); System.out.println(u1.name); // ariel User u2 = u1; //(A) u2.name = "muriel"; //(B) System.out.println(u1.name); // muriel } }

One would want to know as to what meaning to give to the following statement in line (A) above

     User u2 = u1; 

There is only one meaning that Java associates with this kind of an initialization: the variable u2 gets a copy of the same object reference that u1 is holding. In other words, after this initialization, both u1 and u2 have references to the same object, that is to the same chunk of memory. Any changes made to u2 will be reflected in u1. That's what the above program tries to show. When we change u2's name member to muriel in line (B), u1's name member undergoes the same change—because both u1 and u2 are pointing to exactly the same object in the memory.

But what if we wanted u2 to refer to a copy of the object to which u1 is holding a reference? We may need to do so because we anticipate modifying the copy without changing the original object. This can be done by invoking the clone() function that every object inherits from Object. In the next section, we discuss cloning in greater detail.




Programming With Objects[c] A Comparative Presentation of Object-Oriented Programming With C++ and Java
Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java
ISBN: 0471268526
EAN: 2147483647
Year: 2005
Pages: 273
Authors: Avinash Kak

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net