Main Content

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.

For a basic example, seeCreating a Simple Class.

MATLAB®classes that do not explicitly define any class constructors 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:

classdefConstructorDesign < BaseClass1propertiesComputedValueendmethodsfunctionobj = ConstructorDesign(a,b,c)%% Pre Initialization %%% Any code not using output argument (obj)ifnargin == 0% Provide values for superclass constructor% and initialize other inputsa = someDefaultValue; args{1} = someDefaultValue; args{2} = someDefaultValue;else% When nargin ~= 0, assign to cell array,% which is passed to supclass constructorargs{1} = b; args{2} = c;endcompvalue = myClass.staticMethod(a);%% Object Initialization %%% Call superclass constructor before accessing object% You cannot conditionalize this statementobj = obj@BaseClass1(args{:});%% Post Initialization %%% Any code, including access to objectobj.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 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 (seeOutput Object Suppressed).

  • If you create a class constructor, ensure it can be called with no input arguments. SeeNo 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 areturnstatement.

  • Calls to superclass constructors cannot be conditional. You cannot place superclass construction calls in loops, conditions, switches, try/catch, or nested functions. See没有康迪特ional Calls to Superclass Constructorsfor 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.

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, seeEnumeration Class Constructor Calling Sequence.

For information on creating object arrays in the constructor, seeConstruct 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. SeeControl Sequence of Constructor Calls

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 propertyAas the first statement because the objectobjhas already been assigned to an instance ofMyClass.

functionobj = 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 ([])或属性中指定的默认值efinition block.

For example, this constructor operates on the input arguments to assign the value of theValueproperty.

functionobj = MyClass(a,b,c) obj.Value = (a + b) / c;...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 isobjand the object is reference asobj:

% obj is the object being constructedfunctionobj = MyClass(arg) obj.propert1 = arg*10; obj.method1;...end

For more information on defining default property values, seeProperty 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 classConstructOnLoadattribute is set totrue,loadfunction 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 (x(1:9,1)) 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:

functionobj = MyClass(a,b,c)ifnargin > 0 obj.A = a; obj.B = b; obj.C = c;...endend

For ways to handle superclass constructors, seeBasic Structure of Constructor Methods.

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:

classdefMyClass < SuperClassmethodsfunctionobj = MyClass(a,b,c,d) obj@SuperClass(a,b);...endendend

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 theclassdefdoes 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 theclassdefline.

classdefMyClass < SuperClass1 & SuperClass2

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

没有康迪特ional 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).

To call a superclass constructor with different arguments that depend on some condition, build a cell array of arguments and provide one call to the constructor.

For example, theCubeclass constructor calls the superclassShapeconstructor using default values when theCubeconstructor is called with no arguments. If theCubeconstructor is called with four input arguments, then passupvectorandviewangleto the superclass constructor:

classdefCube < ShapepropertiesSideLength = 0 Color = [0 0 0]endmethodsfunctioncubeObj = Cube(length,color,upvector,viewangle)% Assemble superclass constructor argumentsif输入参数个数= = 0 super_args {1} = (0 0 1);super_args {2}= 10;elseifnargin == 4 super_args{1} = upvector; super_args{2} = viewangle;elseerror('Wrong number of input arguments')end% Call superclass constructorcubeObj@Shape(super_args{:});% Assign property values if providedifnargin > 0 cubeObj.SideLength = length; cubeObj.Color = color;end...end...endend

Zero or More Superclass Arguments

To support a syntax that calls the superclass constructor with no arguments, provide this syntax explicitly.

Suppose in the case of theCubeclass example, all property values in theShapesuperclass and theCubesubclass have default values specified in the class definitions. Then you can create an instance ofCubewithout specifying any arguments for the superclass or subclass constructors.

Here is how you can implement this behavior in theCubeconstructor:

methodsfunctioncubeObj = Cube(length,color,upvector,viewangle)% Assemble superclass constructor argumentsifnargin == 0 super_args = {};elseifnargin == 4 super_args{1} = upvector; super_args{2} = viewangle;elseerror('Wrong number of input arguments')end% Call superclass constructorcubeObj@Shape(super_args{:});% Assign property values if providedifnargin > 0 cubeObj.SideLength = length; cubeObj.Color = color;end...endend

More on Subclasses

SeeDesign Subclass Constructorsfor information on creating subclasses.

Implicit Call to Inherited Constructor

MATLAB passes arguments implicitly from a default subclass constructor to the superclass constructor. This behavior eliminates the need to implement a constructor method for a subclass only to pass arguments to the superclass constructor.

For example, the following class constructor requires one input argument (adatetimeobject), which the constructor assigns to theCurrentDateproperty.

classdefBaseClassWithConstrpropertiesCurrentDatedatetimeendmethodsfunctionobj = BaseClassWithConstr(dt) obj.CurrentDate = dt;endendend

Suppose that you create a subclass ofBaseClassWithConstr, but your subclass does not require an explicit constructor method.

classdef SubclassDefaultConstr < BaseClassWithConstr ... end

你可以构造一个对象的SubclassDefaultConstrby calling its default constructor with the superclass argument:

obj = SubclassDefaultConstr(datetime);

For information on subclass constructors, seeSubclass ConstructorsandDefault Constructor.

Errors During Class Construction

For handle classes, MATLAB calls thedeletemethod when an error occurs under the following conditions:

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

  • An earlyreturnstatement is present in the code before the error.

MATLAB calls thedeletemethod on the object, thedeletemethods for any objects contained in properties, and thedeletemethods for any initialized base classes.

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

For information on how objects are destroyed, seeHandle Class Destructor.

Output Object Suppressed

You can suppress the assignment of the class instance to theansvariable 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.

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

classdefMyAppmethodsfunctionobj = MyApp...ifnargout == 0 clearobjendend...endend

When a class constructor does not return an object, MATLAB does not trigger themeta.classInstanceCreatedevent.

Related Topics