System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
This program generates the following output:
ob1 == ob2: true
ob1 == ob3: false
As you can see, the equals( ) method inside Test compares two objects for equality and
returns the result. That is, it compares the invoking object with the one that it is passed. If
they contain the same values, then the method returns true. Otherwise, it returns false. Notice
that the parameter o in equals( ) specifies Test as its type. Although Test is a class type created
by the program, it is used in just the same way as Java's built-in types.
One of the most common uses of object parameters involves constructors. Frequently, you
will want to construct a new object so that it is initially the same as some existing object. To do
this, you must define a constructor that takes an object of its class as a parameter. For example,
the following version of Box allows one object to initialize another:
// Here, Box allows one object to initialize another.
class Box {
double width;
double height;
double depth;
// Notice this constructor. It takes an object of type Box.
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor
used when no dimensions specified
Box() {
width = -1;
// use -1 to indicate
height = -1;
// an uninitialized
depth = -1;
// box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home