|
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.
|