可以說我有列表具有不同的對象
class Person {
String Age;
String Name;
}
Class Employee {
int Salary;
String Name;
}
我有這些類,其在列表中的各種實例。 我創建了2個獨立的功能,接受List<Person>
和List<Employee>
並顯示內容。 但我想創建一個通用函數,它接受任何對象的列表並執行顯示部分。
請幫我
感謝 陽光
可以說我有列表具有不同的對象
class Person {
String Age;
String Name;
}
Class Employee {
int Salary;
String Name;
}
我有這些類,其在列表中的各種實例。 我創建了2個獨立的功能,接受List<Person>
和List<Employee>
並顯示內容。 但我想創建一個通用函數,它接受任何對象的列表並執行顯示部分。
請幫我
感謝 陽光
最簡單的解決方法是讓Employee
繼承Person
。這很自然,因爲員工最有可能是是個人。他們甚至分享了一些屬性,如Name
(你已經在你的代碼中)和Age
。
class Person {
String Age;
String Name;
}
class Employee extends Person {
int Salary;
// String Name; not needed anymore, inherited from Person
}
然後,就足夠了的人List<Person>
,在那裏你可以同時存儲對象類型的列表。
如果您仍然需要保持它們分開出於任何原因,您可以添加一個通用的父類或接口。理想的情況下添加必要的方法(如顯示),進入界面,讓類實現他們:
interface Human {
void showMe();
}
class Person implements Human {
String Age;
String Name;
public void showMe() { System.out.println("I am a Person!"); }
}
class Employee implements Human {
int Salary;
String Name;
public void showMe() { System.out.println("I am an Employee!"); }
}
然後可以使用的Human
個列表來存儲對象類型。迭代變得非常容易:
List<Human> humanList = new ArrayList<>();
// ... Populate the list with Persons and Employees
for(Human human : humanList) {
human.showMe();
}
我應該'已經讓員工擴展人,所以你可以有一個通用的功能來顯示。
另一種方式可以是具有相同顯示功能但具有兩種不同實現的Person和Employee的通用接口。
我沒有測試過,但是這樣的事情:
什麼有員工public interface MyInterface{
public void display();
}
class Person implments MyInterface{
String Age;
String Name;
@Override
public void display(){
//Logic to print the data
}
}
Class Employee implments MyInterface{
int Salary;
String Name;
@Override
public void display(){
//Logic to print the data
}
}
public class MyTest{
public static void main(String[] args){
List<MyInterface> myList = new ArrayList<MyInterface>();
MyInterface p = new Person();
MyInterface e = new Person();
myList.add(p);
myList.add(e);
printMyList(myList);
}
private void printMyList( List<MyInterface> myList){
for(MyInterface my:myList){
my.display();
}
}
}
擴展人與使用人的一個列表? – Davz