MATLAB Object-Oriented Programming

(Joyce) #1
end
end

Zero or More Superclass Arguments

To support a syntax that calls the superclass constructor with no arguments, provide this
syntax explicitly.

Suppose in the case of the Cube class example, all property values in the Shape
superclass and the Cube subclass have default values specified in the class definitions.
Then you can create an instance of Cube without specifying any arguments for the
superclass or subclass constructors.

Here is how you can implement this behavior in the Cube constructor:

methods
function cubeObj = Cube(length,color,upvector,viewangle)
% Assemble superclass constructor arguments
if nargin == 0
super_args = {};
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
end

More on Subclasses

See “Design Subclass Constructors” on page 12-9 for information on creating
subclasses.

9 Methods — Defining Class Operations

Free download pdf