Previous: Inheritance, Up: classdef
Classes [Contents][Index]
There are two intrinsically different types of classdef
classes, whose
major difference is the behavior regarding variable assignment. The first type
are value classes:
classdef value_class properties prop1 endproperties methods function obj = set_prop1 (obj, val) obj.prop1 = val; endfunction endmethods endclassdef
Assigning an object of that class to another variable essentially creates a new object:
>> a = value_class (); >> a.prop1 = 1; >> b = a; >> b.prop1 = 2; >> b.prop1 ⇒ ans = 2 >> a.prop1 ⇒ ans = 1
But that also means that you might have to assign the output of a method that changes properties back to the object manually:
>> a = value_class (); >> a.prop1 = 1; >> a.set_prop1 (3); ⇒ ans = <object value_class> >> ans.prop1 ⇒ ans = 3 >> a.prop1 ⇒ ans = 1
The second type are handle classes. Those classes have to be derived from
the abstract handle
class:
classdef handle_class < handle properties prop1 endproperties methods function set_prop1 (obj, val) obj.prop1 = val; endfunction endmethods endclassdef
In the following example, the variables a
and b
refer to the
very same object of class handle_class
:
>> a = handle_class (); >> a.prop1 = 1; >> b = a; >> b.prop1 = 2; >> b.prop1 ⇒ ans = 2 >> a.prop1 ⇒ ans = 2
Object properties that are modified by a method of an handle class are changed persistently:
>> a.set_prop1 (3); >> a.prop1 ⇒ ans = 3