Java: Putting Your Class to Good Use - dummies

Java: Putting Your Class to Good Use

By Barry Burd

The Employee class in the listing has no main method, so there’s no starting point for executing code. To fix this deficiency, the programmer writes a separate program with a main method and uses that program to create Employee instances.

This code listing shows a class with a main method — one that puts the code to the test.

import static java.lang.System.out;
public class Employee {
    private String name;
    private String jobTitle;
    public void setName(String nameIn) {
        name = nameIn;
    public String getName() {
        return name;
    public void setJobTitle(String jobTitleIn) {
        jobTitle = jobTitleIn;
    public String getJobTitle() {
        return jobTitle;
    public void cutCheck(double amountPaid) {
        out.printf("Pay to the order of %s ", name);
        out.printf("(%s) ***$", jobTitle);
        out.printf("%,.2fn", amountPaid);

According to this listing, each employee has seven features. Two of these features are fairly simple. Each employee has a name and a job title. (In the listing, the Employee class has a name field and a jobTitle field.)

import java.util.Scanner;
public class DoPayroll {
    public static void main(String args[])
                                  throws IOException {
        Scanner diskScanner =
            new Scanner(new File("EmployeeInfo.txt"));
        for (int empNum = 1; empNum <= 3; empNum++) {
    static void payOneEmployee(Scanner aScanner) {
        Employee anEmployee = new Employee();

To run the code, your hard drive must contain a file named EmployeeInfo.txt.

The DoPayroll class in the second listing has two methods. One of the methods, main, calls the other method, payOneEmployee, three times. Each time around, the payOneEmployee method gets stuff from the EmployeeInfo.txt file and feeds this stuff to the Employee class’s methods.

Here’s how the variable name anEmployee is reused and recycled:

  • The first time that payOneEmployee is called, the statement anEmployee = new Employee() makes anEmployee refer to a new object.

  • The second time that payOneEmployee is called, the computer executes the same statement again. This second execution creates a new incarnation of the anEmployee variable that refers to a brand-new object.

  • The third time around, all the same stuff happens again. A new anEmployee variable ends up referring to a third object.

The whole story is pictured here.

Three calls to the payOneEmployee method.
Three calls to the payOneEmployee method.