186k views
1 vote
Create a class Book with two private int fields, numPages and currentPage. Supply a constructor that takes one parameter and sets numPages to that value and currentPage to 1. Provide accessor methods for both fields. Also provide a method nextPage that increments currentPage by 1, but only if currentPage is less than numPages.

1 Answer

0 votes

Answer:

The code is in the explanation.

Step-by-step explanation:

/*Creating the class*/

public class Book{

/*Here we put the attributes of the class;

In our case, they are the two private ints*/

private int numPages;

private int currentPage;

/*Here is the constructor.

The constructor always has the same name as the class

In (), are the parameters.*/

public Book(int numberOfPages){

numPages = numberOfPages; /*sets numPages to the value

of the parameter*/

currentPage = 1; /*sets currentPage to 1*/

}

/*An acessor method is a method with which we can get the value of a variable*/

/*Acessor method for numPages*/

/*numPages is an int, so the acessor method returns an int*/

public int getnumPages(){

return numPages;

}

/*Acessor method for currentPage*/

public int getcurrentPage(){

return currentPage;

}

/*Method next page*/

/*This method does not return anything, so it is a void method*/

public void nextPage(){

/*Verify that currentPage is less than numPages*/

if (currentPage < numPages){

currentPage = currentPage + 1;

}

}

}

User Gawayne
by
5.2k points