Main Content

Save and Load Objects from Class Hierarchies

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.

  • The MySuper class defines a loadobj method to enable an object of this class to be loaded directly.

  • The subclass loadobj method calls a method named reload after it constructs the subclass object.

  • reload first calls the superclass reload method to assign superclass property values and then assigns the subclass property value.

classdef MySuper
   properties
      X
      Y
   end
   methods
      function S = saveobj(obj)
         S.PointX = obj.X;
         S.PointY = obj.Y;
      end
      function obj = reload(obj,S)
         obj.X = S.PointX;
         obj.Y = S.PointY;
      end
   end
   methods (Static)
      function obj = loadobj(S)
         if isstruct(s)
            obj = MySuper;
            obj = reload(obj,S);
         end
      end
   end
end

Call the superclass saveobj and loadobj methods from the subclass saveobj and loadobj methods.

classdef MySub < MySuper
   properties
      Z
   end
   methods
      function S = saveobj(obj)
         S = saveobj@MySuper(obj);
         S.PointZ = obj.Z;
      end
      function obj = reload(obj,S)
         obj = reload@MySuper(obj,S);
         obj.Z = S.PointZ;
      end
   end
   methods (Static)
      function obj = loadobj(S)
         if isstruct(s)
            obj = MySub;
            obj = reload(obj,S);
         end
      end
   end
end

Related Topics