8.2 OBJECT REFERENCE IN JAVA


8.2 OBJECT REFERENCE IN JAVA

While a class-type object in C++ can be accessed directly, or via a pointer, or via a reference, in Java there is only one mode of accessing non-primitive objects—by reference. But the concept "reference" in Java does not have the same meaning as "reference" in C++.

While a C++ reference is simply another name for an object that was created previously, a Java reference is really more like a pointer, albeit one that cannot be dereferenced and that cannot be subject to any pointer arithmetic.

Let's say that with a Java class User defined as

      class User {           private String name;           private int age;           public User( String nam, int a ) { name = nam; age = a; }      } 

we declare a variable u as follows:

      User u = new User( "Orpheus", 109 ); 

With a declaration and initialization such as this, in Java we say that u is holding a reference to an object of type User. The C++ analogy here would be

      User* p = new User( "Orpheus", 109 ); 

which would cause p to hold a memory address that points to an object of type User.




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