Question: Creating a Simple Class and Testing It in JAVA Goal Create a class called Book that represents a book in a library. The Book class

Creating a Simple Class and Testing It in JAVA
Goal
Create a class called Book that represents a book in a library. The Book class should have attributes, constructors, and methods that help manage book information. Then, write a small program to create Book objects and test the class.
Steps to Complete the Assignment
Step 1: Define a Simple Class
Create a new file called Book.java.
Define a class named Book.
Add the following private data members to the class:
String title
String author
int pages
double price
Step 2: Create Constructors
Inside the Book class, create two constructors:
A default constructor that initializes title, author to empty strings, and pages, price to 0.
A parameterized constructor that takes title, author, pages, and price as parameters and initializes the class variables accordingly.
Step 3: Add Methods to the Class
Create public methods for the class:
public void displayBookInfo(): Prints the book's title, author, pages, and price.
public void updatePrice(double newPrice): Updates the price of the book to the value provided by newPrice.
Step 4: Create a Test Class
Create another file called Main.java.
In Main.java, include the necessary imports (import java.util.*; if needed).
Write the main() function that performs the following:
Create a default Book object using the default constructor and call displayBookInfo() to show initial values.
Create another Book object using the parameterized constructor and call displayBookInfo().
Use the updatePrice() method to update the price of the book and display the updated information using displayBookInfo().
Step 5: Compile and Test
Compile both Book.java and Main.java.
Run the program and ensure the following works:
Both constructors properly initialize objects.
The displayBookInfo() method displays the correct book information.
The updatePrice() method correctly updates the price.
Sample Output
When you run the program, you should see output similar to the following:
Default Book Info:
Title:
Author:
Pages: 0
Price: 0.0
Book Info:
Title: The Great Gatsby
Author: F. Scott Fitzgerald
Pages: 180
Price: 10.99
Updated Book Price:
Title: The Great Gatsby
Author: F. Scott Fitzgerald
Pages: 180
Price: 12.99

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!