MATLAB Object-Oriented Programming

(Joyce) #1

  • Object initialization — Call superclass constructors.

  • Post initialization — Perform any operations related to the subclass, including
    referencing and assigning to the object, call class methods, passing the object to
    functions, and so on.


This code illustrates the basic operations performed in each section:

classdef ConstructorDesign < BaseClass1
properties
ComputedValue
end
methods
function obj = ConstructorDesign(a,b,c)

%% Pre Initialization %%
% Any code not using output argument (obj)
if nargin == 0
% Provide values for superclass constructor
% and initialize other inputs
a = someDefaultValue;
args{1} = someDefaultValue;
args{2} = someDefaultValue;
else
% When nargin ~= 0, assign to cell array,
% which is passed to supclass constructor
args{1} = b;
args{2} = c;
end
compvalue = myClass.staticMethod(a);

%% Object Initialization %%
% Call superclass constructor before accessing object
% You cannot conditionalize this statement
obj = obj@BaseClass1(args{:});

%% Post Initialization %%
% Any code, including access to object
obj.classMethod(arg);
obj.ComputedValue = compvalue;
...
end
...
end

9 Methods — Defining Class Operations

Free download pdf