In: Computer Science
Invoice Class - Create a class called Invoice that a hardware store might use to represent an invoice for an item sold at the store. An Invoice should include four pieces of information as instance variables—a part number (type String), a part description (type String), a quantity of the item being purchased (type int) and a price per item (double).
Write a test app named InvoiceTest that demonstrates class Invoice’s capabilities. Create two Invoice objects, print their state, and invoice amounts.
(Java Programming)
Java Program:
package invoicedriver;
class Invoice {
//Private data members
private String partNumber;
private String partDescription;
private int quantity;
private double pricePerItem;
//Constructor
public Invoice(String partNumber, String partDescription, int
quantity, double pricePerItem) {
this.partNumber = partNumber;
this.partDescription = partDescription;
//Checking values
if(quantity < 0) {
this.quantity = 0;
}
else {
this.quantity = quantity;
}
if(pricePerItem < 0) {
this.pricePerItem = 0.0;
}
else {
this.pricePerItem = pricePerItem;
}
}
//Setter and Getter methods
public String getPartNumber() {
return partNumber;
}
public void setPartNumber(String partNumber) {
this.partNumber = partNumber;
}
public String getPartDescription() {
return partDescription;
}
public void setPartDescription(String partDescription) {
this.partDescription = partDescription;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
//Checking values
if(quantity < 0) {
this.quantity = 0;
}
else {
this.quantity = quantity;
}
}
public double getPricePerItem() {
return pricePerItem;
}
public void setPricePerItem(double pricePerItem) {
//Checking values
if(pricePerItem < 0) {
this.pricePerItem = 0.0;
}
else {
this.pricePerItem = pricePerItem;
}
}
//Method that calculates the invoice amount
public double getInvoiceAmount() {
return (this.quantity * this.pricePerItem);
}
}
public class InvoiceDriver {
//Main method
public static void main(String[] args) {
//Creating objects
Invoice inv1 = new Invoice("P101", "Android Mobiles", 10,
23.5);
Invoice inv2 = new Invoice("P201", "Tablet", 5, 14.9);
//Printing result
System.out.println("\nInvoice 1: \n\n Part Number: " +
inv1.getPartNumber() + "\n Description: " +
inv1.getPartDescription() + "\n Invoice Amount: $" +
inv1.getInvoiceAmount());
System.out.println("\nInvoice 2: \n\n Part Number: " +
inv2.getPartNumber() + "\n Description: " +
inv2.getPartDescription() + "\n Invoice Amount: $" +
inv2.getInvoiceAmount());
}
}
________________________________________________________________________________________
Sample Run: