Huy
Huy

Reputation: 11206

Creating multiple objects from a class in a loop... how do I refer to each object?

I'm working on a Java program where I can keep track of my employee payroll. There are two types of employees, hourly and salary.

I have a while loop asking for the input and creating the objects so that I can add as many or as few employees as I want.

When I create my object from my class, I simply use:

HourlyEmployee employee = new HourlyEmployee(type, name, hours, rate);

However, if this is in a while loop, will I be creating several instances of the class type HourlyEmployee with the same name "employee"? Does it even matter if they have the same name (I just want to display the information for each employee on the screen later).

If so, how do I write my code so that the name of each HourlyEmployee object is dynamic as well?

Thanks!

Let me know if you guys want the rest of the code.

Upvotes: 2

Views: 3433

Answers (3)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

Try this,

  1. Create an abstract class called Employee,

  2. Then 2 concrete classes HourlyEmployee and SalaryEmployee.

  3. Use ArrayList to store the employees, having same names wont create a clash, but Map would have been a better option where u can have Ids as unique keys to identify employees even though they have same names.

Eg:

public void addEmp(Employee employee){

ArrayList<? extends Employee> emp;

 while(true){   // Use a boolean variable to terminate the loop at certain conditions

    for (Employee e : emp) {

        e.add(employee);


     }

}

Upvotes: 0

dshapiro
dshapiro

Reputation: 1107

Yes, you will be create several HourlyEmployee objects with the name "employee". As this question sounds a little homework-y, I won't give an example, but I will recommend that you investigate making an array of HourlyEmployee objects.

Upvotes: 2

NPE
NPE

Reputation: 500953

The way to do it is to put all Employee objects into a collection.

A good starting point is this tutorial.

Upvotes: 5

Related Questions