Skip to content
Advertisement

Java: reading objects from file into different derived classes

I have class Employee, and two derived classes Hourly and Salary. Instantiations of those derived classes are placed in the same Array List called employeeList. When I read these objects from file using ois.readObject() how can I ensure the data ends up in the appropriate derived class? Thank you!

Advertisement

Answer

Note: I am not familiar with ObjectInputStream, so I am not exactly sure if this dynamic dispatch would work here, but I recommend giving this a try:

You could have your employee interface look like this:

interface Employee {
    // Whatever other methods you have defined
    
    void populateFieldsFromObject(Object obj);
}

Then each subclass would implement this method differently:

class HourlyEmployee implements Employee {

    // Other methods/fields...

    @override
    void populateFieldsFromObject(Object obj) {
        if (!(obj instanceof HourlyEmployee)) {
            throw new IllegalArugmentException("Object not of correct type");
        }
        HourlyEmployee objEmp = (HourlyEmployee)Object;
        this.hourly = objEmp.hourly;
    }
}

class SalaryEmployee implements Employee {

    // Other methods/fields...

    @override
    void populateFieldsFromObject(Object obj) {
        if (!(obj instanceof SalaryEmployee)) {
            throw new IllegalArugmentException("Object not of correct type");
        }
        SalaryEmployee objEmp = (SalaryEmployee)Object;
        this.salary = objEmp.salary;
    }
}

Then you can just iterate through your List of employees, and call: employee.populateFieldsFromObject(ois.readObject());, as Dynamic Dispatch should automatically determine which method to call based on the type of the object.

Let me know if this works.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement