MATLAB Object-Oriented Programming

(Joyce) #1
Whether this method can add objects of class double and the user-defined class depends
on how you implement the method.

When p and q are objects of different classes, MATLAB applies the rules of precedence to
determine which method to use.

“Object Precedence in Method Invocation” on page 9-47 provides information on how
MATLAB determines which method to call.

Operator Precedence

Overloaded operators retain the original MATLAB precedence for the operator. For
information on operator precedence, see “Operator Precedence”.

Sample Implementation — Addable Objects


The Adder class implements addition for objects of this class by defining a plus method.
Adder defines addition of objects as the addition of the NumericData property values.
The plus method constructs and returns an Adder object whose NumericData property
value is the result of the addition.

The Adder class also implements the less than operator (<) by defining a lt method. The
lt method returns a logical value after comparing the values in each object
NumericData property.

classdef Adder
properties
NumericData
end
methods
function obj = Adder(val)
obj.NumericData = val;
end
function r = plus(obj1,obj2)
a = double(obj1);
b = double(obj2);
r = Adder(a + b);
end
function d = double(obj)
d = obj.NumericData;
end
function tf = lt(obj1,obj2)
if obj1.NumericData < obj2.NumericData

17 Specialize Object Behavior

Free download pdf