AP Computer Science Encapsulation Question

<p>Hey guys~! I have another 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:</p>

<p>



public interface Player
{
    /* Return an integer that represents a move in a game. */
    int getMove();</p>

<pre><code>/* Display the status of the game for this Player after
 * implementing the next move. */
void updateDisplay();
</code></pre>

<p>}




public class HumanPlayer implements Player
{
    private String myName;</p>

<pre><code>//constructors not shown ...

//code to implement getMove and updateDisplay not shown ...

public String getName()
{ /* implementation not shown */ }
</code></pre>

<p>}</p>

<p>public class ExpertPlayer extends HumanPlayer implements Comparable
{
    private int myRating;</p>

<pre><code>//constructors not shown ...

public int compareTo(Object ob)
{ /* implementation not shown */ }
</code></pre>

<p>}


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;
}


</p>

<p>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 are valid. Can someone please explain this?</p>

<p>myRating is a private variable in the ExpertPlayer class, but the method is inside of this class so it can access it.</p>

<p>What he said. While it’s generally bad form to muck around with private variables of other objects, as long as they’re in the same class you CAN. So any ExpertPlayer object can access myRating of any other one.</p>

<p>Got it, thanks so much :D</p>

<p>I’ll be sure to remember that. xD and amarkov this is the second time uv helped me understand a Barron’s problem ^^</p>