Programming lesson
Building an Employee Class in Java: A Step-by-Step OOP Tutorial for ICS 141
Learn how to implement classes and objects in Java by building an Employee class for an HR application. This tutorial covers instance variables, constructors, getters/setters, methods, and a driver class with error handling, perfect for ICS 141 Assignment 2.
Introduction to Classes and Objects in Java
Object-oriented programming (OOP) is essential for building scalable applications. In this tutorial, you'll learn to create a custom Employee class and a driver class to test it, similar to the ICS 141 – 02 Assignment 2 requirements. By the end, you'll be comfortable with instance variables, constructors, accessor methods, and calculation methods. This knowledge is widely used in HR systems, payroll apps, and even game leaderboards—think of how a game like Fortnite tracks player stats with classes.
Step 1: Setting Up the Project
Open Eclipse and create a new Java project named HRApplication. Inside the src folder, create a class called Employee. This class will represent an employee in a company. We'll also create EmployeeDriver (another class with the main method) to test everything.
Step 2: Declaring Instance Variables and Constants
Instance variables store data unique to each object. According to good OOP practices, they should be private. For the Employee class, declare:
private String name;private double hourlyRate;private int hours;
Also declare a constant for tax rate. Constants use the final keyword and are typically public static final. For example:
public static final double TAX = 0.15;This tax rate (15%) is used for calculations later. In real-world apps, tax rates vary by state—similar to how different games have different scoring rules.
Step 3: Constructor and Getters/Setters
A constructor initializes an object when it's created. Write a constructor that takes three parameters:
public Employee(String name, double hourlyRate, int hours) {
this.name = name;
this.hourlyRate = hourlyRate;
this.hours = hours;
}Getters and setters provide controlled access to private fields. For example:
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getHourlyRate() { return hourlyRate; }
public void setHourlyRate(double hourlyRate) { this.hourlyRate = hourlyRate; }
public int getHours() { return hours; }
public void setHours(int hours) { this.hours = hours; }Also override toString() to display employee info:
@Override
public String toString() {
return "Employee: " + name + ", Hourly Rate: $" + hourlyRate + ", Hours: " + hours;
}Step 4: Creating the Driver Class (EmployeeDriver)
In EmployeeDriver, write the main method. Use a sentinel loop to repeatedly ask for employee data. Example structure:
public class EmployeeDriver {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String choice = "yes";
while (choice.equalsIgnoreCase("yes")) {
System.out.print("Enter name: ");
String name = scanner.nextLine();
System.out.print("Enter hourly rate: ");
double rate = scanner.nextDouble();
System.out.print("Enter hours worked: ");
int hours = scanner.nextInt();
scanner.nextLine(); // consume newline
// Validate inputs
if (rate < 0 || hours < 0) {
System.out.println("Error: Rate and hours must be non-negative.");
} else {
Employee myEmployee = new Employee(name, rate, hours);
System.out.println(myEmployee.toString());
}
System.out.print("Continue? (yes/no): ");
choice = scanner.nextLine();
}
scanner.close();
}
}This loop continues until the user types "no". Input validation ensures robustness—a key grading criterion.
Step 5: Adding Calculation Methods (Part 4)
After the lecture, add these methods to the Employee class:
Calculate Gross Pay (Before Taxes)
public double calculateGrossPay() {
return hourlyRate * hours;
}Calculate Tax Amount
public double calculateTax() {
return calculateGrossPay() * TAX;
}Calculate Net Pay (After Taxes)
public double calculateNetPay() {
return calculateGrossPay() - calculateTax();
}Total Taxes Withheld (Company-wide)
This method would sum taxes for all employees. For simplicity, here's a static version:
public static double totalTaxWithheld(Employee[] employees) {
double total = 0;
for (Employee emp : employees) {
total += emp.calculateTax();
}
return total;
}In the driver, call these methods on the employee object and display results. For instance:
System.out.println("Gross Pay: $" + myEmployee.calculateGrossPay());
System.out.println("Tax: $" + myEmployee.calculateTax());
System.out.println("Net Pay: $" + myEmployee.calculateNetPay());Testing and Best Practices
Run your program with various inputs: normal values, zero hours, negative rates (should show error). Ensure no runtime errors. Use meaningful variable names and consistent indentation. Comment your code where necessary.
This assignment mirrors real-world payroll systems used by companies like ADP or Gusto. Understanding classes and objects is foundational for building such applications. Just as a game like League of Legends uses a Champion class with stats like health and damage, your Employee class encapsulates employee data and behaviors.
Conclusion
You've created a complete Employee class with instance variables, constructor, getters/setters, toString, and calculation methods. The driver class demonstrates object instantiation, input validation, and method calls. This tutorial aligns with ICS 141 Assignment 2 requirements and prepares you for more advanced OOP concepts like inheritance and polymorphism.
Practice by adding more features, such as overtime pay or multiple tax brackets. Happy coding!