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?

That's excellent reasoning, but unfortunately (and against primary intuition), that's not how encapsulation works in Java.

See, when a member variable/method is declared private, it means that it can not be accessed by the code in *other* classes. However, there is nothing stopping a function in one ExpertPlayer from accessing the private variables of other ExpertPlayer objects that it has nothing to do with.

The 'privateness' of it applies only to the location of the variable the code itself (which goes back to Java's roots in C/C++).

Very good question, though.

Really?! I didn't know that... wow, thanks so much~!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.