当前位置: 首页 > 知识库问答 >
问题:

在不进行类型转换的情况下访问父类型的arraylist中的特定子类型方法,只有在运行时才知道子类型的创建

欧金鹏
2023-03-14

我有以下父类:

public class Employee {
    private String name;

    public Employee(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

和2个扩展父类的子类:

public class FullTimeEmployee extends Employee {
    private double salary;

    public FullTimeEmployee(String name, double salary) {
        super(name);
        this.salary = salary;
    }

    public double getSalary() {
        return salary*2;
    }
}

public class PartTimeEmployee extends Employee {
    private double salary;

    public PartTimeEmployee(String name, double salary) {
        super(name);
        this.salary = salary;
    }   

    public double getSalary() {
        return salary;
    }   
}
public class EmployeeApplication {

    public static void displayInfo(Employee employee) {
        
        // How do I access the method getSalary() that belong to the specific type determined on runtime?
        System.out.println(employee.getSalary()); //  <--- ???
    }
    
    
    public static void main(String[] args) {
        
        Scanner keyboardInput = new Scanner(System.in);
            
        System.out.println("Type of employee to add into arraylist: ");
        String userInput = keyboardInput.nextLine();
        
        // ArrayList to contain information about employees
        ArrayList<Employee> employeeAL = new ArrayList<Employee>();
        
        // Type of employee being created and added into ArrayList is dynamic and only known at run time based on user input
        if(userInput.equals("full")) {
            employeeAL.add(new FullTimeEmployee("John", 1000));
        }
        else {
            employeeAL.add(new PartTimeEmployee("John", 500));
        }
        
        displayInfo(employeeAL.get(0));
        
        keyboardInput.close();      
    }
}   
// Parent
public class Employee {
    private String name;

    public Employee(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
    
    // ADDED THIS <----
    public double getSalary() {
        return 0.0;
    }
}

// Child
public class FullTimeEmployee extends Employee {
    private double salary;

    public FullTimeEmployee(String name, double salary) {
        super(name);
        this.salary = salary;
    }

    // ADDED THIS <----
    @Override
    public double getSalary() {
        return salary*2;
    }
}

我做错了什么?最好的Java编码实践是什么?

共有1个答案

南门新知
2023-03-14

您可以将Employee实现为抽象,并添加getSalary()作为强制Employee的子类实现该方法的抽象方法

public abstract class Employee {
    private String name;

    public Employee(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
    
    abstract protected double getSalary();
}
 类似资料: