MATLAB Object-Oriented Programming

(Joyce) #1

that is called by the subclass constructor. Therefore, building an array in the superclass
constructor can create a heterogeneous array.


If a superclass constructor returns a heterogeneous array to the subclass constructor,
MATLAB generates an error (see “Potential Error” on page 10-38).


Initialize Array in Superclass Constructor


To avoid errors, initialize the object array explicitly in the superclass constructor. For
example, use repelem in the superclass constructor to initialize the array before
initializing the superclass part of the objects. Initializing the array ensures that all
elements assigned into the array are of the same class as the obj argument.


In this code, the superclass constructor creates one object for each element in the input
argument, arg:


method
function obj = SuperClass(arg)
...
n = numel(arg);
obj = repelem(obj,1,n);
for k = 1:n
obj(k).SuperProp = arg(k);
end
...
end
end


The subclass constructor calls the superclass constructor to pass the required argument
array, a:


method
function obj = SubClass(a)
obj = obj@SuperClass(a);
for k = 1:numel(a)
obj(k).SubProp = a(k);
end
end
end


Heterogeneous Array Constructors 10-

Free download pdf