简体   繁体   English

如何将抽象 Class 中的列表传递给另一个 class?

[英]How to pass a List from an abstract Class to another class?

Employee is my abstract class and it has FixedPosition as a daughter class. Employee是我的抽象 class,它有FixedPosition作为子 class。 Company has a method called addEmployee() that must receive a type Employee and then add the List from Employee to its own List. Company 有一个名为 addEmployee() 的方法,该方法必须接收一个 Employee 类型,然后将来自 Employee 的 List 添加到它自己的 List 中。

Company company = new Company("Hi");
List<Employee> employees = new ArrayList<>();

Later I fill up my List but I don't know how to send a type Employee into the method from Company.后来我填写了我的列表,但我不知道如何将类型 Employee 从公司发送到方法中。

employees.add(new FixedPosition(name, occupation, salary, monthsContract));
company.addEmployee();

Your method addEmployee() has no argument.您的方法addEmployee()没有参数。 Rewrite it so that it gets an employee object solves your problem.重写它,让它得到一个员工 object 解决了你的问题。

public void addEmployee( Employee e ) {
    this.employees.add(e);
}

Your company class should have the list of employees.您的公司 class 应该有员工名单。

It seems that you need to overload method addEmployee in your Company class to support handling of an employee list:您似乎需要在Company class 中重载方法addEmployee以支持处理员工列表:

public void addEmployee(List<Employee> employees) {
    this.employees.addAll(employees);
}

Or you can call existing Company method with a single employee in a loop:或者,您可以在循环中使用单个员工调用现有的Company方法:

employees.forEach(company::addEmployee);

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

相关问题 如何将列表或数组列表从AsyncTask类传递给另一个类 - how to pass list or arraylist from an AsyncTask class to another class 如何从另一个类调用抽象内部类的方法? - How to call a method of an abstract inner class from another class? 使用流 java 从另一个抽象类中过滤和排序列表 - Filter and order a list from another abstract class using stream java 从另一个抽象类扩展的抽象类的重要性是什么 - What is the importance of abstract class that extends from another abstract class 如何从另一个类调用非静态抽象方法 - How to call a non static abstract method from another class 如何传递包含另一个可包裹 class 列表的可包裹 class? - How to pass a Parcelable class which contains a list of another parcelable class? 如何传递对抽象类的引用 - Java - How to pass reference to abstract class - Java 如何将类名传递给抽象超类构造函数? - How to pass in a class name in to abstract superclass constructor? 如果将类更改为抽象类并将其扩展到另一个类中,如何使用类中的对象? - how do you use the objects from a class if you change it to an abstract class and extend it in another class? 如何获取一个类的值并将其传递给另一个类? - How to get and pass a value from a class to another?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM