OOP in Matlab: Assign Default Value to Class Property Using An Instance of Another Class

This tutorial illustrates an example of OOP in Matlab, assign default property of a class using an instance of another class. Especially, it shows how different when value and handle object behave when assigned as default values to class properties.

Let’s first define two classes in two separate m-files:

%--- Class defined in file ContClass.m
 
classdef ContClass
    properties
        TimeProp = datestr(now); 
    end
end
 
%--- Class defined in file ClassExp.m
 
classdef ClassExp
    properties
        ObjProp = ContClass;
    end
end

Now we run following commands:

>> a = ClassExp;
>> a.ObjProp.TimeProp
ans =
02-Feb-2015 12:07:22
 
>> b = ClassExp;
>> b.ObjProp.TimeProp
ans =
02-Feb-2015 12:07:22

As can be seen, even though a and b are different instances created at different time, they contain same time intormation. The underlying reason is as following:

Matlab evaluates the expression ObjProp = ContClass in class definition only when the class is initialized. Initialization occurs before the class is first used. After initialization, the value of property ObjProp returned by the expression is part of the class definition and are fixed as default value when creating all instances of the class. Each instance of the class uses the result of the initial evaluation without reevaluation.

However, if you clear a class, then Matlab re-initializes the class by re-evaluating the expressions that are part of the class definition.

>> clear all
>> a = ClassExp;
>> a.ObjProp.TimeProp
ans =
02-Feb-2015 16:27:05
 
>> b = ClassExp;
>> b.ObjProp.TimeProp
ans =
02-Feb-2015 16:27:05

As can be seen, after executing ‘clear all‘, the class property is initialized to a new time.

Note that if you use ‘clear a b‘ instead of using ‘clear all‘, the class property will not be re-initialized. I don’t know why this happen. If you know the reason, please kindly leave your comment. Thanks in advance.

Since the contained class ContClass is a value class, each instance of the ClassExp class has its own copy of the object (two separate objects are created). Therefore, for example, if you change b.ObjProp.TimeProp, this change does not affect a.ObjProp.TimeProp

>> b.ObjProp.TimeProp = datestr(now);
>> b.ObjProp.TimeProp
ans =
02-Feb-2015 16:28:41
 
>> a.ObjProp.TimeProp
ans =
02-Feb-2015 16:27:05

However,  if we define the ContClass as handle class, then only one ContClass instance is created, and each instance of ClassExp class carry a copy of the handle of this object. Therefore, when b.ObjProp.TimeProp changes, it propagate to a.ObjProp.TimeProp.

>> clear all
>> a = ClassExp;
>> a.ObjProp.TimeProp
ans =
02-Feb-2015 20:43:23
>> b = ClassExp;
>> b.ObjProp.TimeProp
ans =
02-Feb-2015 20:43:23
 
>> b.ObjProp.TimeProp = datestr(now);
>> b.ObjProp.TimeProp
ans =
02-Feb-2015 20:43:47
>> a.ObjProp.TimeProp
ans =
02-Feb-2015 20:43:47

 

Tags
Subject
Category
Coding language