我有抽象类Human,这是其他两个类Student和Worker的extendet。我正在尝试填写两个数组列表。类型为Student的ArrayList和类型为Worker的ArrayList。
public abstract class Human {
private String fName = null;
private String lName = null;
public String getfName() {
return fName;
}
public Human(String fName, String lName) {
super();
this.fName = fName;
this.lName = lName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
}
public class Student extends Human {
private String grade = null;
public Student(String fName, String lName, String grade) {
super(fName, lName);
this.grade = grade;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
}
public class Worker extends Human {
private int weekSalary = 0;
private int workHoursPerDay = 0;
public Worker(String fName, String lName, int weekSalary, int workHoursPerDay) {
super(fName, lName);
this.weekSalary = weekSalary;
this.workHoursPerDay = workHoursPerDay;
}
public int getWorkSalary() {
return weekSalary;
}
public void setWorkSalary(int workSalary) {
this.weekSalary = workSalary;
}
public int getWorkHoursPerDay() {
return workHoursPerDay;
}
public void setWorkHoursPerDay(int workHoursPerDay) {
this.workHoursPerDay = workHoursPerDay;
}
public int moneyPerHour() {
return weekSalary / (5 * workHoursPerDay);
}
}
public class Program {
public static void main(String[] args) {
ArrayList<Student> student = new ArrayList<>();
ArrayList<Worker> worker = new ArrayList<>();
}
}
答案 0 :(得分:2)
当然,只需添加学生:
ArrayList<Student> students = new ArrayList<>(); // note: students
students.add(new Student("Jens", "Nenov", "A+"));
你可以为工人做几乎完全相同的事情。如果要使用循环,请执行以下操作:
for (int i=0; i<50; i++) {
students.add(new Student("Jens"+i, "Nenov", "A+"));
}
这将创建一个名单后面有不同数字的新学生列表。但是,如果您想要不同的数据,那么数据需要来自某个地方。例如,您可以从用户输入中获取数据:
Scanner input = new Scanner(System.in);
for ...
System.out.println("Enter a first name:");
String firstname = input.nextLine();
...
students.add(new Student(firstname, lastname, grade));