MATLAB Object-Oriented Programming

(Joyce) #1

classdef MyClass
...
methods
function objPkgClass = PkgName.PkgClass(objMyclass)
...
end
end
end


You cannot define a converter method that uses dots in the name in a separate file. Define
package-class converters in the classdef file.


Converters and Subscripted Assignment


When you make a subscripted assignment statement like:


A(1) = myobj;


MATLAB compares the class of the Right-Side variable to the class of the Left-Side
variable. If the classes are different, MATLAB attempts to convert the Right-Side variable
to the class of the Left-Side variable. To do this conversion, MATLAB first searches for a
method of the Right-Side class that has the same name as the Left-Side class. Such a
method is a converter method, which is similar to a typecast operation in other
languages.


If the Right-Side class does not define a method to convert from the Right-Side class to
the Left-Side class, MATLAB calls the Left-Side class constructor. passing it the Right-
Side variable.


For example, suppose that you make the following assignments:


A(1) = objA; % Object of class ClassA
A(2) = objB; % Object of class ClassB


MATLAB attempts to call a method of ClassB named ClassA. If no such converter
method exists, MATLAB software calls the ClassA constructor, passing objB as an
argument. If the ClassA constructor cannot accept objB as an argument, then MATLAB
returns an error.


Use cell arrays to store objects of different classes.


Object Converters
Free download pdf