Page 289 - Introduction to Programming with Java: A Problem Solving Approach
P. 289

                Figure 7.4
Car2Driver class that drives the Car2 class in Figure 7.5
anathema to strings. We must use the equals method for strings! Thus, to check whether the make in- stance variable has the same value in the calling object and the passed-in parameter object, we do this:
this.make.equals(otherCar.make)
Hmmm . . . . Does it strike you as odd to use the String class’s equals method inside of our Car2 class’s equals method? That’s perfectly OK—the compiler doesn’t care if two methods happen to have the same name as long as they are in different classes. That’s part of the beauty of encapsulation!
Can you think of another way to write the body of the Car2 class’s equals method? We might have used that boolean expression to the right of the return keyword as the condition of an if statement and thenputreturn trueintheifclauseandreturn falseintheelseclause.Butthatwouldhave been a harder and longer way to do the same thing—and probably more confusing, too, because it would have required more parentheses. Although Figure 7.5’s return statement might appear at first glance to be a Cerberean rat’s nest,1 most veteran programmers would consider it to be rather elegant.
1 You probably already know what a “rat’s nest” is—a tangled mess. But how about “Cerberean”? In Greek mythology, Cerberus is a vicious three-headed dog creature that guards the entrance to Hades (the world of the dead). We say our return statement might appear to be a Cerberean rat’s nest because it’s complicated and it has three parts. Which would you rather meet in a dark alley—a vicious three-headed dog creature or a complicated return statement?
7.4 Testing Objects for Equality 255
 /**************************************************************
*
Car2Driver.java
Dean & Dean
This class is a demonstration driver for the Car2 class.
**************************************************************/
*
*
*
public class Car2Driver
{
public static void main(String[] args)
{
Car2 nathanCar = new Car2();
Car2 nickCar = new Car2();
nathanCar.setMake("Audi");
nathanCar.setYear(1998);
nathanCar.setColor("green");
nickCar.setMake("Audi");
nickCar.setYear(1998);
nickCar.setColor("green");
if (nathanCar.equals(nickCar))
   }
// end class Car2Driver
}
}
// end main
{
System.out.println("Cars have identical features.");
     Apago PDF Enhancer
Note how equals method call is embedded in an if condition.
 



























































   287   288   289   290   291