0% found this document useful (0 votes)
14 views6 pages

Java Classes for Invoice, Employee, Date

Uploaded by

wwangyibo17
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views6 pages

Java Classes for Invoice, Employee, Date

Uploaded by

wwangyibo17
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Chapter 3

1. (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). Your class should have a constructor
that initializes the four instance variables. Provide a set and a get method for each instance variable.
In addition, provide a method named getInvoiceAmount that calculates the invoice amount (i.e.,
multiplies the quantity by the price per item), then returns the amount as a double value. If the
quantity is not positive, it should be set to 0. If the price per item is not positive, it should be set to 0.
Write a test application named InvoiceTest that demonstrates class Invoice’s capabilities.

Program:
//[Link]
package CH_3;
public class Invoice{
private int partNumber;
private String partDescription;
private int quantity;
private double unitPrice;

public Invoice(int partNumber, String partDescription, int quantity, double unitPrice){


setPartNumber(partNumber);
setDescription(partDescription);
setQuantity(quantity);
setUnitPrice(unitPrice);
}
public void setPartNumber(int num){
partNumber = num;
}
public void setDescription(String des){
partDescription = des;
}
public void setQuantity(int count){
if(count > 0){
quantity = count;
}else{
quantity = 0;
}
}
public void setUnitPrice(double price){
if(price > 0){
unitPrice = price;
}else{
unitPrice = 0;
}
}
public int getPartNumber(){
1
return partNumber;
}
public String getDescription(){
return partDescription;
}

public int getQuantity(){


return quantity;
}
public double getUnitPrice(){
return unitPrice;
}
public double getInvoiceAmount(){
return getQuantity() * getUnitPrice();
}
public void displayInfo() {
[Link]("Invoice");
[Link]("Part Number: %d \n",partNumber);
[Link]("Part Description: %s \n",partDescription);
[Link]("Quantity: %d \n",quantity);
[Link]("Unit Price: $%.2f \n",unitPrice);
[Link]("Invoice Amount: $%.2f \n\n",getInvoiceAmount());
}
}

//[Link]
package CH_3;
public class InvoiceTest{
public static void main(String[] args){
Invoice saw = new Invoice(123, "Saw", 7, 32.5);
Invoice hammer = new Invoice(124, "Hammer", 18, 12.0);

[Link]();
[Link]();
}
}

Output:
Invoice
Part Number: 123
Part Description: Saw
Quantity: 7
Unit Price: $32.50
Invoice Amount: $227.50

Invoice
Part Number: 124
2
Part Description: Hammer
Quantity: 18
Unit Price: $12.00
Invoice Amount: $216.00

2. (Employee Class) Create a class called Employee that includes three instance variables—a first
name (type String), a last name (type String) and a monthly salary (double). Provide a constructor
that initializes the three instance variables. Provide a set and a get method for each instance variable.
If the monthly salary is not positive, do not set its value. Write a test application named
EmployeeTest
that demonstrates class Employee’s capabilities. Create two Employee objects and display each
object’s yearly salary. Then give each Employee a 10% raise and display each Employee’s yearly
salary again.

Program:
//[Link]
package CH_3;
public class Employee{
private String firstName;
private String lastName;
private double monthlySalary;
public Employee(String fName, String lName, double monthlySalary){
setFirstName(fName);
setLastName(lName);
setMonthlySalary(monthlySalary);
}
public void setFirstName(String fName){
firstName = fName;
}
public String getFirstName(){
return firstName;
}
public void setLastName(String lName){
lastName = lName;
}
public String getLastName(){
return lastName;
}
public void setMonthlySalary(double salary){
if(salary > 0)
monthlySalary = salary;
}
public double getMonthlySalary(){
return monthlySalary;
}
public void setRaise(double percentage){
double increasedAmount = (monthlySalary / 100) * percentage;
3
double newSalary = monthlySalary + increasedAmount;
setMonthlySalary(newSalary);
}

public double getYearlySalary(){


return getMonthlySalary() * 12;
}
public void displayInfo(){
[Link]("Employee Info");
[Link]("First Name: %s \n",firstName);
[Link]("Last Name: %s \n",lastName);
[Link]("Monthly Salary: $%.2f \n",monthlySalary);
[Link]("Yearly Salary: $%.2f \n\n",getYearlySalary());
}

//[Link]
package CH_3;
public class EmployeeTest{
public static void main(String[] args){

Employee employee1 = new Employee("Frank", "Freddy", 1000);


[Link]();

Employee employee2 = new Employee("Jack", "Jackson", 768);


[Link]();

[Link]("\nAfter 10% raises:\n");


[Link](10);
[Link](10);

[Link]();
[Link]();

}
}

Output:
Employee Info
First Name: Frank
Last Name: Freddy
Monthly Salary: $1000.00
Yearly Salary: $12000.00

Employee Info
First Name: Jack
4
Last Name: Jackson
Monthly Salary: $768.00
Yearly Salary: $9216.00

After 10% raises:

Employee Info
First Name: Frank
Last Name: Freddy
Monthly Salary: $1100.00
Yearly Salary: $13200.00

Employee Info
First Name: Jack
Last Name: Jackson
Monthly Salary: $844.80
Yearly Salary: $10137.60

3. (Date Class) Create a class called Date that includes three instance variables—a month (type
int), a day (type int) and a year (type int). Provide a constructor that initializes the three instance
variables and assumes that the values provided are correct. Provide a set and a get method for each
instance variable. Provide a method displayDate that displays the month, day and year separated by
forward slashes (/). Write a test application named DateTest that demonstrates class Date’s
capabilities.
Program:
//[Link]
package CH_3;
public class Date{
private int month;
private int day;
private int year;

public Date(int month, int day, int year){


setMonth(month);
setDay(day);
setYear(year);
}
public void setMonth(int value){
month = value;
}
public int getMonth(){
return month;
}

public void setDay(int value){


day = value;
5
}

public int getDay(){


return day;
}
public void setYear(int value){
year = value;
}
public int getYear(){
return year;
}
// display date
public void displayDate(){
[Link]("\nDate: %d/%d/%d", getMonth(), getDay(), getYear());
}
}

//[Link]
package CH_3;
import [Link];

public class DateTest{


public static void main(String[] args){
Scanner input = new Scanner([Link]);

[Link]("Enter Day: ");


int day = [Link]();
[Link]("Enter Month: ");
int month = [Link]();
[Link]("Enter Year: ");
int year = [Link]();

Date date = new Date(day,month,year);


[Link]();

}
}

Output:
Enter Day: 29
Enter Month: 12
Enter Year: 2023
Date: 29/12/2023

Common questions

Powered by AI

The displayInfo method serves the role of providing a formatted representation of the class's data and calculated values, functioning as an integral tool for debugging and user communication. In the Invoice class, it outputs details like part number, description, quantity, unit price, and invoice amount, providing a summary of transaction data. Similarly, in the Employee class, it prints the employee's name and salary information, offering a complete view of employee compensation. This method helps in verifying that instances hold correct values and behave as expected .

If the Invoice class did not handle negative values appropriately, it could lead to logical errors in computations, such as producing negative invoice amounts if the quantity or unit price were improperly set to negative values. This oversight would cause significant discrepancies in financial records, potentially leading to financial misreporting. Proper handling of negative values ensures data integrity and reliable calculations, safeguarding against errors in business processes relying on this class .

The pros of having a test application like InvoiceTest include ensuring that the class behaves as expected in various situations, serving as a form of documentation of the class's functionality, and identifying bugs early in the development cycle. Test applications also facilitate regression testing to confirm that changes do not introduce new issues. However, cons include potential maintenance overhead as tests must be updated alongside code changes, and the risk of incomplete test coverage unless comprehensive test cases are implemented. Test applications might also not fully capture complex real-world scenarios .

The setRaise method in the Employee class adjusts an employee's salary based on a given percentage increase. It calculates the increase by determining a percentage of the current monthly salary and adds this amount to the salary. This dynamic adjustment capability allows for modifying employee compensation efficiently, supporting scenarios like annual raises or merit-based pay increases. By handling both the computation and assignment internally, it provides a seamless mechanism for updating salary data .

The Invoice class's instance variables (partNumber, partDescription, quantity, and unitPrice) store essential item details. Methods such as set and get for each variable allow controlled access and modification of these data fields. The getInvoiceAmount method utilizes the quantity and unitPrice variables to compute the total invoice amount by multiplication. The displayInfo method leverages these computed values and stored data to provide formatted output, showcasing the combination of these methods with the instance variables to maintain a coherent and functional unit of work .

The Invoice class sets the quantity and unit price to 0 if they are negative inputs. This is achieved through conditional checks in the setQuantity and setUnitPrice methods. If the quantity is less than or equal to zero, it defaults to 0, and similarly, if the unit price is less than or equal to zero, it also defaults to 0 .

Without input validation for month, day, and year, the Date class might accept invalid dates, such as February 30th or month 13, potentially leading to erroneous data handling and downstream processing errors. This could compromise the integrity of applications relying on accurate date information for scheduling, reporting, or age calculations. Such lapses in validation increase the risk of exceptions in operations that depend on valid date ranges and could result in unpredictable behavior or system crashes .

Assuming correct input values in constructors can simplify class design by reducing the complexity needed to handle and process validation logic within the class itself. This places the responsibility of data validation on the calling code or user interface, allowing the class to focus solely on its core functionality. However, this approach requires ensuring that either the calling code performs appropriate validation or that the class offers ways to safely modify data post-construction if needed .

Enhancements to the Employee class could include validation on inputs to ensure the salary is not only positive but also reasonable within the industry standards. Furthermore, the class could include detailed compensation reports, track salary changes over time, handle different types of employment contracts, and integrate performance metrics for dynamic raises. Adding localization support for different currencies and integrating tax calculations could further enhance its utility .

Encapsulation in the Employee class is implemented through private instance variables (firstName, lastName, monthlySalary) with public set and get methods. This structure hides the internal representation and allows controlled access to modify and retrieve data, preventing unauthorized or unintended modifications. Encapsulation is crucial for maintaining class integrity and abstraction, which facilitates change management and enhances code modularity, allowing changes to internal implementations without affecting external interfaces .

You might also like