Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create an abstract class named Book. Include a String field for the book’s title

ID: 3762421 • Letter: C

Question

Create an abstract class named Book. Include a String field for the book’s title and a double field for the book’s price. Within the class, include a constructor that requires the book title, and add two get methods—one that returns the title and one that returns the price. Include an abstract method named setPrice(). Create two child classes of Book: Fiction and NonFiction. Each must include a setPrice() method that sets the price for all Fiction Books to $24.99 and for all NonFiction Books to $37.99. Write a constructor for each subclass, and include a call to setPrice() within each. Write an application demonstrating that you can create both a Fiction and a NonFiction Book and display their fields. Save the files as Book.java, Fiction.java, NonFiction.java, and UseBook.java.

Explanation / Answer

Solution:

Book.java

package com.chegg.nancy.solutions;

public abstract class Book {
   String title;
   double price;

   Book(String title) {
       this.title = title;
   }

   public String getTitle() {
       return title;
   }

   public double getPrice() {
       return price;
   }

   public abstract void setPrice(double price);

}

Fiction.java

package com.chegg.nancy.solutions;

public class Fiction extends Book {

   Fiction(String title) {
       super(title);
       setPrice(24.99);
   }

   @Override
   public void setPrice(double price) {
       this.price = price;
   }

   public String toString() {
       return "Title = " + title + " and Price = " + price + "$";
   }
}

NonFiction.java

package com.chegg.nancy.solutions;

public class NonFiction extends Book{

   NonFiction(String title) {
       super(title);
       setPrice(37.99);
   }

   @Override
   public void setPrice(double price) {
       this.price = price;
   }
  
   public String toString(){
       return "Title = " + title + " and Price = " + price + "$";
   }
}

UseBook.java

package com.chegg.nancy.solutions;

public class UseBook {

   public static void main(String[] args) {
       Fiction fObj = new Fiction("Fiction Book");
       System.out.println(fObj);
      
       Fiction nfObj = new Fiction("Non Fiction Book");
       System.out.println(nfObj);
   }
}

Output:

Title = Fiction Book and Price = 24.99$
Title = Non Fiction Book and Price = 37.99$

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote