简体   繁体   English

在一个循环中从一个类创建多个对象……如何引用每个对象?

[英]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. 我正在开发一个Java程序,可以跟踪我的员工工资。 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. 我有一个while循环,要求输入并创建对象,以便可以根据需要添加任意数量的员工。

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"? 但是,如果这是在while循环中,我是否将创建几个名称为“ employee”的类型为HourlyEmployee的实例? 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? 如果是这样, 我该如何编写代码,使每个HourlyEmployee对象的名称也动态化?

Thanks! 谢谢!

Let me know if you guys want the rest of the code. 让我知道你们是否需要其余的代码。

The way to do it is to put all Employee objects into a collection. 这样做的方法是将所有Employee对象放入一个集合中。

A good starting point is this tutorial . 教程是一个很好的起点。

Yes, you will be create several HourlyEmployee objects with the name "employee". 是的,您将创建几个名为“ employee”的HourlyEmployee对象。 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. 因为这个问题听起来有点功课,所以我不举一个例子,但是我建议您研究制作一个HourlyEmployee对象数组。

Try this, 尝试这个,

  1. Create an abstract class called Employee, 创建一个名为Employee的抽象类,

  2. Then 2 concrete classes HourlyEmployee and SalaryEmployee. 然后是2个具体的类HourlyEmployee和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. 使用ArrayList来存储具有相同名称的员工,不会产生冲突,但是Map会是一个更好的选择,在这种情况下,即使Ids as unique keys具有相同的名称,您也可以将Ids as unique keys来标识员工。

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);


     }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM