Page 546 - Introduction to Programming with Java: A Problem Solving Approach
P. 546
512 Chapter 13 Inheritance and Polymorphism
/************************************************
*
Car.java
Dean & Dean
This defines and compares cars.
************************************************/
*
*
*
public class Car
{
private String make; // car's make
private int year;
// car's listed year
private String color; // car's color
//*********************************************
public Car(String make, int year, String color)
{
this.make = make;
this.year = year;
this.color = color;
} // end Car constructor
//*********************************************
Apago PDF Enhancer
public boolean equals(Car otherCar) ⎫ {⎪
}
// end class Car
return
otherCar != null && ⎪
} // end
⎬
⎪ year == otherCar.year && ⎪
color.equals(otherCar.color); ⎭
equals
This overrides the Object class’s equals method.
make.equals(otherCar.make) &&
Figure 13.1 Car class which defines equals to mean same instance variable values
instance variable and the other made by the color instance variable. As explained in Chapter 3, these calls to String’s equals method check to see if two different strings have the same character sequence.
Intheequalmethod’sreturnexpression,noticetheotherCar!= nullsubexpression.If this evaluates to false (indicating that otherCar is null), Java’s short-circuit evaluation keeps the computer from trying to use a null reference to access the other car’s make and color reference vari- ables. Such short-circuit evaluation prevents runtime errors. You should always strive to make your code robust. In this case, that means you should consider the possibility of someone passing in a null value for otherCar. If null gets passed in and there’s no test for null, the JVM generates a runtime error when it sees otherCar.make. This is a fairly common error—attempting to access a member from a null reference variable—and you can avoid it easily. Just test for null prior to accessing the member. For our equals method, if otherCar is null, then the otherCar != null subexpression is false, and