0

This might be an easy answer but I'm new and my professor hasn't been much help, also feel free to correct my terminology. Essentially I have a class "Employee" and I'm trying to add several instances of it to an ArrayList to be printed later in Main. It looks kind of like this:

    public Employee(int id, String name, String bday, String gender, String job, int org)
{
    this.id = id;
    this.name = name;
    this.bday = bday;
    this.gender = gender;
    this.job = job;
    this.org = org;
}

All I really need to know how to do is print the values I've managed to assign to the constructor i.e. when I call a specific object from the ArrayList I'll be able to print the object's specific id, name, etc. I figured out that I can do it by creating a method for each individual variable but that would be really messy and inefficient, I'm looking for one method to call that would be able to do this.

1 Answers1

0

Override Object.toString() in Employee. Something like,

@Override
public String toString() {
    return String.format("Employee id=%d, name=%s, bday=%s, gender=%s, job=%s, org=%s",
            id, name, bday, gender, job, org);
}

Then whenever you try and print it, the toString of Employee will be invoked.

System.out.println(new Employee(1, "Test", "A Birthday",
        "Yes", "Something", "Somewhere"));
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249