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

                256 Chapter 7 Object-Oriented Programming—Additional Details
 /****************************************************************
*
Car2.java
Dean & Dean
This class implements equals functionality for a car.
****************************************************************/
*
*
*
public class Car2
{
private String make;
private int year;
private String color;
//************************************************************
public void setMake(String make)
{
}
this.make = make;
public void setYear(int year)
{
}
this.year = year;
        Apago PDF Enhancer
public void setColor(String color)
{
}
this.color = color;
//************************************************************
// This method tests whether two cars hold the same data.
public boolean equals(Car2 otherCar)
  }
// end class Car2
{
return this.make.equals(otherCar.make) && ⎫ this.year == otherCar.year && ⎬ this.color.equals(otherCar.color); ⎭
 } // end equals
This compares all instance variables.
Figure 7.5 Car2 class with equals method
Suppose you want uppercase colors to be considered the same as lowercase colors. In other words, you want a silver 2005 Ford to be considered the same as a Silver 2005 Ford. How should you change the code to handle that? Use equalsIgnoreCase instead of equals when comparing the color strings:
this.color.equalsIgnoreCase(otherCar.color)


























































   288   289   290   291   292