gpt4 book ai didi

java - 我如何区分这些对象(即 FirstLevelEmployee 和 SecondLevelEmployee)并且我想打印 SecondLevelEmployee 的详细信息?

转载 作者:行者123 更新时间:2023-12-02 03:15:16 25 4
gpt4 key购买 nike

在下面的代码中,我创建了父类和子类对象。这些对象存储在数组列表中。我的问题是如何区分这些对象,并且我只想检索二级员工详细信息。

package com.javahonk.controller;

import java.util.ArrayList;
import java.util.ListIterator;

class FirstLevelEmployee {
int id;
String name;
double salary;

FirstLevelEmployee(int id, String name, double salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
}

class SecondLevelEmployee extends FirstLevelEmployee {
int experience;

SecondLevelEmployee(int id, String name, double salary, int experience) {
super(id, name, salary);
this.experience = experience;
}
}

public class EmployeeDemo {

public static void main(String[] args) {
ArrayList<FirstLevelEmployee> emps = new ArrayList<>();
emps.add(new FirstLevelEmployee(1, "aaa", 20000.00));
emps.add(new FirstLevelEmployee(2, "bbb", 10000.00));
emps.add(new FirstLevelEmployee(3, "bbb", 30000.00));
emps.add(new SecondLevelEmployee(4, "zzz", 12000, 2));
emps.add(new SecondLevelEmployee(6, "yyy", 45000.00, 5));
}
}

最佳答案

尝试这样做:

for(FirstLevelEmployee emp : emps){
if(emp instanceof SecondLevelEmployee){
System.out.println(((SecondLevelEmployee)emp).experience);
}
}

您将迭代该数组,并询问给定元素 emp 是否是 SecondLevelEmployee 的实例。如果为 true,您将通过将 emp 转换为 SecondLevelEmployee

来打印它

关于java - 我如何区分这些对象(即 FirstLevelEmployee 和 SecondLevelEmployee)并且我想打印 SecondLevelEmployee 的详细信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40406966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com