MATLAB Object-Oriented Programming

(Joyce) #1

When to Define Constructors


Define a constructor method to perform object initialization that a default constructor
cannot perform. For example, when creating an object of the class requires:


  • Input arguments

  • Initializing object state, such as property values, for each instance of the class

  • Calling the superclass constructor with values that are determined by the subclass
    constructor


Related Information


For information specific to constructing enumerations, see “Enumeration Class
Constructor Calling Sequence” on page 14-8.

For information on creating object arrays in the constructor, see “Construct Object
Arrays” on page 10-2.

If the class being created is a subclass, MATLAB calls the constructor of each superclass
class to initialize the object. Implicit calls to the superclass constructor are made with no
arguments. If superclass constructors require arguments, call them from the subclass
constructor explicitly. See “Control Sequence of Constructor Calls” on page 12-14

Initializing Objects in Constructor


Constructor methods return an initialized object as an output argument. The output
argument is created when the constructor executes, before executing the first line of
code.

For example, the following constructor can assign the value of the object's property A as
the first statement because the object obj has already been assigned to an instance of
MyClass.

function obj = MyClass(a,b,c)
obj.A = a;
...
end

You can call other class methods from the constructor because the object is already
initialized.

9 Methods — Defining Class Operations

Free download pdf