Object Converters
In this section...
“Why Implement Converters” on page 17-12
“Converters for Package Classes” on page 17-12
“Converters and Subscripted Assignment” on page 17-13
Why Implement Converters
You can convert an object of one class to an object of another class. A converter method
has the same name as the class it converts to, such as char or double. Think of a
converter method as an overloaded constructor method of another class. The converter
takes an instance of its own class and returns an object of a different class.
Converters enable you to:
- Use methods defined for another class
- Ensure that expressions involving objects of mixed class types execute properly
- Control how instances are interpreted in other contexts
Suppose that you define a polynomial class. If you create a double method for the
polynomial class, you can use it to call other functions that require inputs of type
double.
p = polynomial(...);
dp = double(p);
roots(dp)
p is a polynomial object, double is a method of the polynomial class, and roots is a
standard MATLAB function whose input arguments are the coefficients of a polynomial.
Converters for Package Classes
Classes defined in packages can have names that are a dot-separated list of names. The
last name is a class and preceding names are packages. Name the conversion methods
using the package qualifiers in the method names. For example, a conversion method to
convert objects of MyClass to objects of the PkgName.PkgClass class uses this method
name:
17 Specialize Object Behavior