MATLAB Object-Oriented Programming

(Joyce) #1
In this case, obj is an object of a class that defines a property called Property1.
Therefore, you can pass a char variable in the parentheses to reference to property:

propName = 'Property1';
obj.(propName)

You can call a method and pass input arguments to the method using another set of
parentheses:

obj.(expression)(arg1,arg2,...)

Using this notation, you can make dynamic references to properties and methods in the
same way you can create dynamic references to the fields of structs.

As an example, suppose that an object has methods corresponding to each day of the
week. These methods have the same names as the days of the week (Monday, Tuesday,
and so on). Also, the methods take as char vector input arguments, the current day of the
month (the date). Now suppose that you write a function in which you want to call the
correct method for the current day.

Use an expression created with the date and datestr functions:

obj.(datestr(date,'dddd'))(datestr(date,'dd'))

The expression datestr(date,'dddd') returns the current day as a char vector. For
example:

datestr(date,'dddd')

ans =

Tuesday

The expression datestr(date,'dd') returns the current date as a char vector. For
example:

datestr(date,'dd')

ans =

11

Therefore, the expression using dot-parentheses (called on Tuesday the 11th) is the
equivalent of:

9 Methods — Defining Class Operations

Free download pdf