MATLAB Object-Oriented Programming

(Joyce) #1

...
end


Call the constructor like any function, passing arguments and returning an object of the
class.


obj = ConstructorDesign(a,b,c);


Guidelines for Constructors



  • The constructor has the same name as the class.

  • The constructor can return multiple arguments, but the first output must be the object
    created.

  • If you do not want to assign the output argument, you can clear the object variable in
    the constructor (see “Output Object Suppressed” on page 9-30).

  • If you create a class constructor, ensure it can be called with no input arguments. See
    “No Input Argument Constructor Requirement” on page 9-25.

  • If your constructor makes an explicit call to a superclass constructor, this call must
    occur before any other reference to the constructed object and cannot occur after a
    return statement.

  • Calls to superclass constructors cannot be conditional. You cannot place superclass
    construction calls in loops, conditions, switches, try/catch, or nested functions. See
    “No Conditional Calls to Superclass Constructors” on page 9-27 for more
    information.


Default Constructor


If a class does not define a constructor, MATLAB supplies a default constructor that takes
no arguments and returns a scalar object whose properties are initialized to property
default values. The default constructor supplied by MATLAB also calls all superclass
constructors with no arguments or with any argument passed to the default subclass
constructor.


When a subclass does not define a constructor, the default constructor passes its inputs to
the direct superclass constructor. This behavior is useful when there is no need for a
subclass to define a constructor, but the superclass constructor does require input
arguments.


Class Constructor Methods
Free download pdf