MATLAB Object-Oriented Programming

(Joyce) #1
loadobj

Define loadobj as a static method. Create an object by calling the class constructor.
Then assign values to properties from the struct passed to loadobj. Use the data to
regenerate properties that were not saved.

methods(Static)
function obj = loadobj(s)
if isstruct(s)
newObj = ClassConstructor;
newObj.Prop1 = s.Prop1;
newObj.Prop2 = s.Prop2
newObj.GraphHandle = plot(s.Data);
obj = newObj;
else
obj = s;
end
end
end

If the load function encounters an error, load passes loadobj a struct instead of an
object. Your loadobj method must always be able to handle a struct as the input
argument. The input to loadobj is always a scalar.

Handle Load Problems


loadobj can handle a struct input even if you are not using a saveobj method.

The GraphExpression class creates a graph of a MATLAB expression over a specified
range of data. GraphExpression uses its loadobj method to regenerate the graph,
which is not saved with the object.

classdef GraphExpression
properties
FuncHandle
Range
end
methods
function obj = GraphExpression(fh,rg)
obj.FuncHandle = fh;
obj.Range = rg;
makeGraph(obj)
end

13 Saving and Loading Objects

Free download pdf