MATLAB Object-Oriented Programming

(Joyce) #1
function obj = MyClass(a,b,c)
if nargin > 0
obj.A = a;
obj.B = b;
obj.C = c;
...
end
end

For ways to handle superclass constructors, see “Basic Structure of Constructor
Methods” on page 9-21.

Subclass Constructors


Subclass constructors can call superclass constructors explicitly to pass arguments to the
superclass constructor. The subclass constructor must specify these arguments in the call
to the superclass constructor and must use the constructor output argument to form the
call. Here is the syntax:

classdef MyClass < SuperClass
methods
function obj = MyClass(a,b,c,d)
obj@SuperClass(a,b);
...
end
end
end

The subclass constructor must make all calls to superclass constructors before any other
references to the object (obj). This restriction includes assigning property values or
calling ordinary class methods. Also, a subclass constructor can call a superclass
constructor only once.

Reference Only Specified Superclasses

If the classdef does not specify the class as a superclass, the constructor cannot call a
superclass constructor with this syntax. That is, subclass constructor can call only direct
superclass constructors listed in the classdef line.

classdef MyClass < SuperClass1 & SuperClass2

MATLAB calls any uncalled constructors in the left-to-right order in which they are
specified in the classdef line. MATLAB passes no arguments with these calls.

9 Methods — Defining Class Operations

Free download pdf