MATLAB Object-Oriented Programming

(Joyce) #1

No Conditional Calls to Superclass Constructors


Calls to superclass constructors must be unconditional. There can be only one call for a
given superclass. Initialize the superclass portion of the object by calling the superclass
constructors before using the object (for example, to assign property values or call class
methods).


To call a superclass constructor with different arguments that depend on some condition,
build a cell array of arguments and provide one call to the constructor.


For example, the Cube class constructor calls the superclass Shape constructor using
default values when the Cube constructor is called with no arguments. If the Cube
constructor is called with four input arguments, then pass upvector and viewangle to
the superclass constructor:


classdef Cube < Shape
properties
SideLength = 0
Color = [0 0 0]
end
methods
function cubeObj = Cube(length,color,upvector,viewangle)
% Assemble superclass constructor arguments
if nargin == 0
super_args{1} = [0 0 1];
super_args{2} = 10;
elseif nargin == 4
super_args{1} = upvector;
super_args{2} = viewangle;
else
error('Wrong number of input arguments')
end


% Call superclass constructor
cubeObj@Shape(super_args{:});


% Assign property values if provided
if nargin > 0
cubeObj.SideLength = length;
cubeObj.Color = color;
end
...
end
...


Class Constructor Methods
Free download pdf