Hey everyone~! I have been studying for the AP Computer Science exam, and I have a question where I think Barron's is wrong, so if someone could confirm whether I am correct or not please let me know! The following code snippets are given:
public interface Player
{
/* Return an integer that represents a move in a game. */
int getMove();
/* Display the status of the game for this Player after
* implementing the next move. */
void updateDisplay();
}
public class HumanPlayer implements Player
{
private String myName;
//constructors not shown ...
//code to implement getMove and updateDisplay not shown ...
public String getName()
{ /* implementation not shown */ }
}
public class ExpertPlayer extends HumanPlayer implements Comparable
{
private int myRating;
//constructors not shown ...
public int compareTo(Object ob)
{ /* implementation not shown */ }
}
Question: Which of the following is correct implementation code for the compareTo method in the ExpertPlayer class?
//Option I
public int compareTo(Object ob)
{
ExpertPlayer rhs = (ExpertPlayer) obj;
if (myRating == rhs.myRating)
return 0;
else if (myRating < rhs.myRating)
return -1;
else
return 1;
}
//Option II
public int compareTo(Object ob)
{
ExpertPlayer rhs = (ExpertPlayer) obj;
return myRating - rhs.myRating;
}
//Option III
public int compareTo(Object ob)
{
ExpertPlayer rhs = (ExpertPlayer) obj;
if (getName().equals(rhs.getName()))
return 0;
else if (getName().compareTo(rhs.getName()) < 0)
return -1;
else
return 1;
}
My argument: Only option III would be valid since myRating is a private variable in the ExpertPlayer class and thus needs getters and setters to access it. Barron's says all options (I, II, and III) are valid. Can someone please explain this?