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 subclasssaveobj
method because thesave
function calls only the most specificsaveobj
method.The subclass
loadobj
method can call the superclassloadobj
, 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 thestruct
.The subclass
saveobj
method calls each superclasssaveobj
method and returns the completedstruct
to thesave
function. Then thesave
function writes thestruct
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 theload
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 aloadobj
method to enable an object of this class to be loaded directly.The subclass
loadobj
method calls a method namedreload
after it constructs the subclass object.reload
first calls the superclassreload
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