MATLAB Object-Oriented Programming

(Joyce) #1

Save and Load Objects from Class Hierarchies


In this section...
“Saving and Loading Subclass Objects” on page 13-33
“Reconstruct the Subclass Object from a Saved struct” on page 13-33

Saving and Loading Subclass Objects


If the most specific class of an object does not define a loadobj or saveobj method, this
class can inherit loadobj or saveobj methods from a superclass.

If any class in the hierarchy defines saveobj or loadobj methods:


  • Define saveobj for all classes in the hierarchy.

  • Call superclass saveobj methods from the subclass saveobj method because the
    save function calls only the most specific saveobj method.

  • The subclass loadobj method can call the superclass loadobj, or other methods as
    required, to assign values to their properties.


Reconstruct the Subclass Object from a Saved struct


Suppose that you want to save a subclass object by first converting its property data to a
struct in the class saveobj method. Then you reconstruct the object when loaded using
its loadobj method. This action requires that:


  • Superclasses implement saveobj methods to save their property data in the struct.

  • The subclass saveobj method calls each superclass saveobj method and returns the
    completed struct to the save function. Then the save function writes the struct to
    the MAT-file.

  • The subclass loadobj method creates a subclass object and calls superclass methods
    to assign their property values in the subclass object.

  • The subclass loadobj method returns the reconstructed object to the load function,
    which loads the object into the workspace.


The following superclass (MySuper) and subclass (MySub) definitions show how to code
these methods.

Save and Load Objects from Class Hierarchies
Free download pdf