Cover Data Structures and Algorithms with Object-Oriented Design Patterns in Java
next up previous contents index

References Types

 

Java allows the creating of user-defined types . A user-defined types is created by defining a class . For example, by defining a class classed Foo, we introduce an new ``type'' that can be used to declare a variable like this:

Foo f;
(Classes are discussed in Section gif).

In Java, every variable that is not one of the primitive types is a reference type . Such a variable can be thought of as a reference to (or a pointer to ) an object of the appropriate type. For example, the variable f defined above is a reference to an object instance of the class Foo.

In Java, class instances must be explicitly created. An instance of a class is created using the new operator like this:

f = new Foo ();
If we follow this with an assignment statement such as
Foo g = f;
then both f and g refer to the same object! Note that this is very different from what happens when you assign one primitive type to another.

A comparison of the the form

if (f == g)
    { /* ... */ }
tests whether the f and g refer to the same object instances. If f and g refer to distinct object instances that happen to be equal, the test still fails. To test whether two distinct object instances are equal, it is necessary to invoke the equals method like this:
if (f.equals(g))
    { /* ... */ }




next up previous contents index

Bruno Copyright © 1998 by Bruno R. Preiss, P.Eng. All rights reserved.