Overriding the equals method

File Player.java contains a class that holds information about an athlete: name, team, and uniform number. File ComparePlayers.java contains a skeletal program that uses the Player class to read in information about two baseball players and determine whether or not they are the same player.

  1. Fill in the missing code in ComparePlayers so that it reads in two players and prints "Same player", if they are the same, and "Different players" if they are different. (You may want to use Player.readPlayer.) The existing code uses the equals method (Player inherits this from the Object class) to determine whether two players are the same. In your lab document, indicate the extent to which the results are what we might expect.

  2. The problem is that the equals method that is inherited from the Object class does only an address comparison, in effect saying that two objects are equal only if they reside at the same memory location, that is, if the variables that hold references to them are aliases. The two Player objects in this program are not aliases, so even if they contain exactly the same information they will not "be equal." To make equals() compare the actual information in the object rather than just checking where it is stored, you can override it with a definition specific to the class. For example, it might make sense to say that two two players are "equal" (the same player) if they are on the same team and have the same uniform number.
  3. POTENTIAL PITFALL: if your code has something like, jerseyNumber.equals(otherPlay.jerseyNumber) you will get an error message something like "cannot invoke equals(int) on the primitive type int". In your lab document describe what this message means. Consider the following code fragment--which would exhibit the same error message--wouldn't you write the conditional clause for the IF statement a bit differently? Please write a better IF statement in your lab document. (Then fix Employee.equals() in the same way.)
  4. int x = 3; int y =3;
    if (x.equals(y)) System.out.println("x is equal to y");

  5. The output statement in ComparePlayers.java uses the equals method, but also tries to print the two Player objects. In the lab document, cut and paste what is printed as the code now exists.


  6. To make the output more readable, add a toString method to your Player class so that we can easily print player objects. The string the function returns should incorporate the values of all the instance variables in some meaningful way, perhaps something like "Joe Smith, of the Tigers, #23". Run the program to double-check that the toString method is working correctly.

  7. Place copies of the output of two runs of your program in your lab document: one for when the players are "equal" and one for when they are not.

Your submission should contain your Java files as well as your laboratory document.