Which of the following method headers would properly define the method needed to make this class Comparable?

Which of the following method headers would properly define the method needed to make this class Comparable?

a)       public boolean comparable(Object cp)
b)       public int comparable(Object cp)
c)       public int compareTo(Object cp)
d)       public int compareTo( )
e)       public boolean compareTo(Object cp)

Consider a class called ChessPiece.  This class has two instance data, String type and int player.  The variable type will store “King”, “Queen”, “Bishop”, etc and the int player will store 0 or 1 depending on whose piece it is.  We wish to implement Comparable for the ChessPiece class.  Assume that, the current ChessPiece is compared to a ChessPiece passed as a parameter.  Pieces are ordered as follows:  “Pawn” is a lesser piece to a “Knight” and a “Bishop”, “Knight” and “Bishop” are equivalent for this example, both are lesser pieces to a “Rook” which is a lesser piece to a “Queen” which is a lesser piece to a “King.”


Answer:  c.

Explanation:  To implement Comparable, you must implement a method called compareTo which returns an int.  Further, since this class will compare this ChessPiece to another, we would except the other ChessPiece to be passed in as a parameter (although compareTo is defined to accept an Object, not a ChessPiece).


Enhancing Classes

Learn More Multiple Choice Question :