Documentation

This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

Class Constructor Methods

Purpose of Class Constructor Methods

A constructor method is a special function that creates an instance of the class. Typically, constructor methods accept input arguments to assign the data stored in properties and return an initialized object.

All MATLAB® classes have a default constructor method. This method returns an object of the class that is created with no input arguments. A class can define a constructor method that overrides the default constructor. An explicitly defined constructor can accept input arguments, initialize property values, call other methods, and perform other operations necessary to create objects of the class.

Basic Structure of Constructor Methods

Constructor methods can be structured into three basic sections:

  • Pre-initialization — Compute arguments for superclass constructors.

  • Object initialization — Call superclass constructors.

  • Post initialization — Perform any operations related to the subclass, including referencing and assigning to the object, call class methods, passing the object to functions, and so on.

This code illustrates the basic operations performed in each section:

classdef ConstructorDesign < BaseClass1
   properties
      ComputedValue
   end
   methods
      function obj = ConstructorDesign(a,b,c)
         
         %% Pre Initialization %%
         % Any code not using output argument (obj)
         if nargin == 0
            % Provide values for superclass constructor
            % and initialize other inputs
            a = someDefaultValue;
            args{1} = someDefaultValue;
            args{2} = someDefaultValue;
         else
            % When nargin ~= 0, assign to cell array,
            % which is passed to supclass constructor
            args{1} = b;
            args{2} = c;
         end
         compvalue = myClass.staticMethod(a);
         
         %% Object Initialization %%
         % Call superclass constructor before accessing object
         % You cannot conditionalize this statement
         obj = obj@BaseClass1(args{:});
         
         %% Post Initialization %%
         % Any code, including access to object
         obj.classMethod(arg);
         obj.ComputedValue = compvalue;
         ...
      end
   ...
   end
...
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 only output argument from a constructor is the object constructed.

  • If you do not want to assign the output argument, you can clear the object variable in the constructor (see Output Object Not Assigned).

  • If you create a class constructor, provide support for no input arguments. See No Input Argument Constructor Requirement.

  • 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 for more information.

  • A class does not need to define a constructor method unless it is a subclass of a superclass whose constructor requires arguments. In this case, you must explicitly call the superclass constructor with the required arguments. See Subclass Constructors

  • If a class does not define a constructor, MATLAB supplies a constructor that takes no arguments and returns a scalar object whose properties are initialized to empty or the values specified as defaults in the property definitions. The constructor supplied by MATLAB also calls all superclass constructors with no arguments.

Related Information

For information specific to constructing enumerations, see Enumeration Class Constructor Calling Sequence.

For information on creating object arrays in the constructor, see Construct Object Arrays.

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

Initializing Objects in Constructor

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

For example, the following constructor function 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.

The constructor also creates an object whose properties have their default values—either empty ([]) or the default value specified in the property definition block.

For example, the following code calls the class method CalculateValue to assign the value of the property Value.

function obj = myClass(a,b,c)
   obj.Value = obj.CalculateValue(a,b);
      ...
end

Referencing the Object in a Constructor

When initializing the object, for example, by assigning values to properties, use the name of the output argument to refer to the object within the constructor. For example, in the following code the output argument is obj and the object is reference as obj:

% obj is the object being constructed
function obj = myClass(arg) 
   obj.propert1 = arg*10;
   obj.method1;
      ...
end

For more information on defining default property values, see Property Default Values.

No Input Argument Constructor Requirement

There are cases where the constructor must be able to be called with no input argument:

  • When loading objects into the workspace. If the class ConstructOnLoad attribute is set to true, the load function calls the class constructor with no arguments.

  • When creating or expanding an object array such that not all elements are given specific values, the class constructor is called with no arguments to fill in unspecified elements (for example, x(10,1) = myclass(a,b,c);). In this case, the constructor is called once with no arguments to populate the empty array elements with copies of this one object.

If there are no input arguments, the constructor creates an object using only default properties values. A good practice is to add a check for zero arguments to the class constructor to prevent an error if either of these two cases occur:

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.

Subclass Constructors

Subclass constructor functions must explicitly call superclass constructors if the superclass constructors require input arguments. The subclass constructor must specify these arguments in the call to the superclass constructor using the constructor output argument. Here is the syntax:

classdef MyClass < SuperClass 
   function obj = MyClass(arg)
      obj@SuperClass(SuperArgList);
         ...
   end
end

The class constructor must make all calls to superclass constructors before any other references to the object. These changes include 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.

classdef MyClass < SuperClass

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

No Conditional Calls to Superclass Constructors

Calls to superclass constructors must be unconditional. There can be only one call for a given superclass. Initialize the superclass portion of the object by calling the superclass constructors before using the object (for example, to assign property values or call class methods).

If you must call superclass constructors with different arguments that depend on some condition, you can build a cell array of arguments and provide one call to the constructor.

For example, the Cube class constructor calls the superclass Shape constructor using default values when the Cube constructor is called with no arguments. If the Cube constructor is called with four input arguments, pass upvector and viewangle to the superclass constructor:

classdef Cube < Shape
   properties
      SideLength = 0
      Color = [0 0 0]
   end
   methods
      function cubeObj = Cube(length,color,upvector,viewangle)
         if nargin == 0
            super_args{1} = [0 0 1];
            super_args{2} = 10;
         elseif nargin == 4
            super_args{1} = upvector;
            super_args{2} = viewangle;
         else
            error('Wrong number of input arguments')
         end
         cubeObj@Shape(super_args{:});
         if nargin > 0 % Use value if provided
            cubeObj.SideLength = length;
            cubeObj.Color = color;
         end
         ...
      end
   ...
   end
end

Zero or More Superclass Arguments

If you must support the 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)
      if nargin == 0 
         super_args = {};
      elseif nargin == 4
         super_args{1} = upvector;
         super_args{2} = viewangle;
      else
         error('Wrong number of input arguments')
      end
      cubeObj@Shape(super_args{:});
      if nargin > 0 
         cubeObj.SideLength = length;
         cubeObj.Color = color;
      end
   ...
   end
end

More on Subclasses

See Subclass Constructors for information on creating subclasses.

Errors During Class Construction

For handle classes, MATLAB calls the delete method when an error occurs under these conditions:

  • A reference to the object is present in the code prior to the error.

  • An early return statement is present in the code before the error.

MATLAB calls the delete method on the object, the delete methods for any objects contained in properties, and the delete methods for any initialized base classes.

Depending on when the error occurs, MATLAB can call the class destructor before the object is fully constructed. Therefore class delete methods must be able to operate on partially constructed objects that might not have values for all properties. For more information, see Support Destruction of Partially Constructed Objects.

For information on how objects are destroyed, see Handle Class Destructor.

Output Object Not Assigned

You can suppress the assignment of the class instance to the ans variable when no output variable is assigned in a call to the constructor. This technique is useful for apps that creates graphical interface windows that hold onto the constructed objects. These apps do not need to return the object.

Use nargout to determine if the constructor has been called with an output argument. For example, the class constructor for the MyApp class clears the object variable, obj, if called with no output assigned:

classdef MyApp
   methods
      function obj = MyApp
         ...
         if nargout == 0
            clear obj
         end
      end
      ...
   end
end

When a class constructor does not return an object, MATLAB does not trigger the meta.class InstanceCreated event.

Related Topics

Was this topic helpful?