76.1k views
2 votes
Create a Book class that has variables name, cost, edition and price. It should have private variables, a public constructor, methods to get and set the variables, and a function that returns the price with a 5% tax. Show how you create two Book object in main. Output the cost of the two Books.

User Verbeia
by
6.5k points

1 Answer

5 votes

Answer:

//Create a public class to test the application

public class BookTest{

//write the main method

public static void main(String []args){

//Create two Book objects

Book book = new Book("Book 1", 2000, "First edition", 2900);

Book book2 = new Book("Book 2", 3000, "First edition", 3900);

//Output the cost of the two books

System.out.println("Cost of first book is " +book.getCost());

System.out.println("Cost of second book is " + book2.getCost());

} //End of main method

} //End of BookTest Class

//Write the Book class

class Book {

//declare all variables and make them private

private String name;

private double cost;

private String edition;

private double price;

//create a public constructor

public Book(String name, double cost, String edition, double price){

this.name = name;

this.cost = cost;

this.edition = edition;

this.price = price;

}

//getter method for name

public String getName(){

return this.name;

}

//setter method for name

public void setName(String name){

this.name = name;

}

//getter method for cost

public double getCost(){

return this.cost;

}

//setter method for cost

public void setCost(double cost){

this.cost = cost;

}

//getter method for edition

public String getEdition(){

return this.edition;

}

//setter method for edition

public void setEdition(String edition){

this.edition = edition;

}

//getter method for price

public double getPrice(){

return this.price;

}

//setter method for price

public void setPrice(double price){

this.price = price;

}

//function to return price with 5% tax

public double priceWithTax(){

return this.price + (0.05 * this.price);

}

}

============================================

Sample Output

Cost of first book is 2000.0

Cost of second book is 3000.0

============================================

Step-by-step explanation:

The code above has been written in Java and it contains comments explaining important parts of the code. Kindly go through those comments. For clarity, the actual lines of code have been written in bold face.

A sample output resulting from a run of the code has also been provided.

User Arsalan Valoojerdi
by
6.7k points