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:

JavaScript

Then each subclass would implement this method differently:

JavaScript

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