Suppose you are implementing the Comparable interface in a class representing a Book, where the ordering is based on the number of pages in the book. Write a compareTo method for this class. You may assume that in the Book class there is an instance variable called numPages and a method called getNumPages.

Answer :

Answer:

Following are the code to this question:

public class Book implements Comparable<Book> //defining a class that inherits the interface

{

int numPage; //defining integer variable numPage

int getNumPage()//defining a method getNumPage

{

return numPage; //use return keyword to return numPage value

}

int compareTo(Book b)//defining a method compareTo that uses Book instance b

{

   //using multiple conditions

if (getNumPage() > b.getNumPage())//defining if block that checks getNumPage method value is greater then instance of getNumPage  

{

return 1; //return value 1

}

else if (getNumPage() == b.getNumPage())//defining else if block that checks method and its instance value is euqal    

{

return 0;//return 0

}

else //defining else block

{

return -1;//return value -1

}

}

}

Explanation:

In the above-given code, a class book is defined, that inherits the interface that is "Comparable<Book>". Inside the class, an integer variable "numPage" and a method "getNumPages" is defined, that returns the "numPage" value.

In the next step, the "compareTo" method is declared, which uses an instance of the book and use the conditional statement.

  • In the if block, It checks the "getNumPages" method value is greater than the instance of the "getNumPages" method if the value is true, it will return "1", otherwise goto else if block.
  • In this block, it will check both "method and instance of method" values are equal, if the condition is true, it will return "0".
  • In the else block, if the above condition is false, it will return the value that is "-1".  

Other Questions