FRQ 2 - Classes
Textbook extends Book class
public class Book{
/** The title and price of the book */
private String title;
private double price;
/** Creates a new Book with given title and price */
public Book(String bookTitle, double bookPrice){
this.title = bookTitle;
this.price = bookPrice;
}
/** Returns the title of the book */
public String getTitle(){
return title; }
/** Returns a string containing the title and price of the Book */
public String getBookInfo(){
return title + "-" + price;
}
}
public class Textbook extends Book{
private int edition;
public Textbook(String title, double price, int editionNum){
super(title,price);
this.edition = editionNum;
}
//constructor calls the title and price from parent class using super
//sets edition num
public int getEdition(){
return edition;
}
//gets the edition
public String getBookInfo(){
return super.getBookInfo() + "-" + edition;
}
//returns the book info with super book info + the edition
public boolean canSubstituteFor(Textbook textbook){
if(getTitle().equals(textbook.getTitle()) && (edition >= textbook.getEdition())){
//checks to see if the current title is equal to the title from the textbook
//AND checks if the edition of the current is equal or greater than the compared textbook
return true;
}else{
return false;
}
}
public static void main(String[] args){
Textbook bio2015 = new Textbook("Biology", 49.75, 2);
Textbook bio2019 = new Textbook("Biology", 39.75, 3);
Textbook math = new Textbook("Calculus", 45.25, 1);
//creates new textbook objects for bio and calc
System.out.println("Get Biology Book Info (2019):");
System.out.println();
System.out.println("Edition: " + bio2019.getEdition());
System.out.println("Book Info: " + bio2019.getBookInfo());
//gets bio book info using getters for edition and book info
System.out.println("----------------------");
System.out.println("Can Substitute For:");
System.out.println();
System.out.println("2019 sub for 2015: " + bio2019.canSubstituteFor(bio2015));
System.out.println("2015 sub for 2019: " + bio2015.canSubstituteFor(bio2019));
System.out.println("2015 sub for math: " + bio2015.canSubstituteFor(math));
//uses can substitute method to check if valid substitution
}
}
Textbook.main(null);