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. Can't get the main method right. Book -
public abstract class Book {
String mBookTitle;
double mPrice;
public Book(String title ){
mBookTitle=title;
}
public String gettitle(){
return mBookTitle;
}
public double getPrice(){
return mPrice;
}
public abstract void setPrice();
}
Fiction -
public class Fiction extends Book{
public Fiction(String title) {
super(title);
setPrice();
}
public void setPrice(){
super.mPrice=24.99;
}
}
NonFiction -
public class NonFiction extends Book{
public NonFiction(String title) {
super(title);
setPrice();
}
public void setPrice(){
super.mPrice=37.99;
}
}
UseBook -
public class UseBook {
public static void main(String[] args){
Book books;
books=new Fiction("A wrinkle in Time");
System.out.println(books.gettitle());
books=new NonFiction("The art of Programming");
System.out.println(books);
}
}
CodePudding user response:
I'm assuming your issue is with printing some random string (for example: NonFiction@15db9742). This is because you are printing the object of NonFiction (books) in your last line in main method, instead of its attribute. Your should change your last line to System.out.println(books.gettitle());
This is just some careless mistake I believe.
CodePudding user response:
Read more about Factory design pattern and how to implement it in Java.
https://www.baeldung.com/creational-design-patterns
Factory is creational design pattern and it can learn you how to deal with these cases.
In addition, to see the object printed normally you should override the toSrting
method like this:
@Override
public String toString() {
return String.format(
"Book (mBookTitle=%s, mPrice=%s)", this.mBookTitle, this.mPrice);
}