MATLAB Object-Oriented Programming

(Joyce) #1

Assign Property Values from Constructor


To assign values to a property from within the class constructor, reference the object that
the constructor returns (the output variable obj):


classdef MyClass
properties
Prop1
end
methods
function obj = MyClass(intval)
obj.Prop1 = intval;
end
end
end


When you assign a property in the class constructor, MATLAB evaluates the assignment
statement for each object you create. Assign property values in the constructor if you
want each object to contain a unique value for that property.


For example, suppose that you want to assign a unique handle object to the property of
another object each time you create one of those objects. Assign the handle object to the
property in the constructor. Call the handle object constructor to create a unique handle
object with each instance of your class.


For more information on constructor methods, see “Referencing the Object in a
Constructor” on page 9-25.


Initialize Properties to Unique Values


MATLAB assigns properties to the specified default values only once when MATLAB loads
the class definition. Therefore, if you initialize a property value with a handle-class
constructor, MATLAB calls this constructor only once and every instance references the
same handle object. If you want a property value to be initialized to a new instance of a
handle object each time you create an object, assign the property value in the constructor.


Property Attributes


All properties have attributes that modify certain aspects of the property's behavior.
Specified attributes apply to all properties in a particular properties block. For example:


Property Definition
Free download pdf