Documentation Center

  • Trials
  • Product Updates

Ordinary Methods

Defining Methods

You can specify methods:

  • Inside of a class definition block

  • In a separate file in the class @-folder

Methods Inside classdef Block

This example shows the definition of a method (the compute function in this example) within the classdef and methods blocks:

classdef ClassName
   methods (AttributeName = value,...)
      function x = compute(obj,inc)
         x = obj.y + inc;
      end % compute method
...
   end % methods block
...
end % classedf

    Note:   Nonstatic methods must include an explicit object variable in the function definition. The MATLAB® language does not support an implicit reference in the method function definition.

Either of the following statements is correct syntax for calling a method where obj is an object of the class defining the compute method:

obj.compute(inc)
compute(obj,inc)

See also Dot Notation vs. Function Notation.

Method attributes apply only to that particular methods block, which is terminated by the end statement.

Methods in Separate Files

You can define class methods in separate files within the class @-folder. In this case, create a function in a separate file having the same name as the function (i.e., functionname.m). If you want to specify attribute values for that method, you must declare the method signature within a methods block in the classdef block . For example:

classdef myClass
   methods (AttributeName = value,...)
      tdata = testdata(obj,arg1,arg2)
...
   end % methods
...
end % classdef

Do not use methods blocks in the separate files. Define the method as a function. Using the example above, the file testdata.m, must contain the definition of the testdata function. Note that the signatures must match.

function tdata = testdata(myClass_object,argument2,argument3)
   ...
end

The following limitations apply to methods defined in separate files:

  • If you want to specify attributes for a method defined in a separate file, you must declare this method in a methods block (specifying attribute values) within the classdef block.

  • The syntax declared in the methods block (if used) must match the method's function line.

  • The separate file must be in the class @-folder.

  • The constructor method must be defined within the classdef block and, therefore, cannot be in a separate file. (See Class Constructor Methods for information on this method.)

  • Set and get property access methods must be defined within the classdef block and, therefore, cannot be in separate files. (See Property Access Methods for information on these methods.)

Determining Which Method Is Invoked

When the MATLAB runtime invokes an ordinary method that has an argument list, it uses the following criteria to determine which method to call

  • The class of the left-most argument whose class is not specified as inferior to any other argument's class is chosen as the dominant class and its method is invoked.

  • If this class does not define the named method, then a function with that name on the MATLAB path is invoked.

  • If no such function exists, MATLAB issues an error indicating that the dominant class does not define the named method.

Dominant Argument

The dominant argument in a method's argument list determines which version of the method or function that the MATLAB runtime calls. Dominance is determined by the relative precedences of the classes of the arguments. In general, user-defined classes take precedence over built-in MATLAB classes. Therefore, the left most argument determines which method to call. However, user-defined classes can specify the relative dominance of specific classes.

For example, suppose classA defines classB as inferior and suppose both classes define a method called combine.

Calling the method with an object of classB and classA:

combine(B,A)

actually calls the combine method of classA because A is the dominant argument.

See Specifying Precedence for information on how to define class precedence.

Dot Notation vs. Function Notation

MATLAB classes support both function and dot notation syntax for calling methods. For example, if setColor is a method of the class of object X, then calling setColor with function notation would be:

X = setColor(X,'red');

The equivalent method call using dot notation is:

X = X.setColor('red')

However, in certain cases, the results for dot notation can differ with respect to how MATLAB dispatching works:

  • If there is an overloaded subsref, it is invoked whenever using dot-notation. That is, the statement is first tested to see if it is subscripted assignment.

  • If there is no overloaded subsref, then setColor must be a method of X. An ordinary function or a class constructor is never called using this notation.

  • Only the argument X (to the left of the dot) is used for dispatching. No other arguments, even if dominant, are considered. Therefore dot notation can call only methods of X; methods of other argument are never called.

A Case Where the Result is Different.  Here is an example of a case where dot and function notation can give different results. Suppose you have the following classes:

  • classA defines a method called methodA that requires an object of classB as one of its arguments

  • classB defines classA as inferior to classB

classdef classB (InferiorClasses = {?classA})
   ...
end

The methodA method is defined with two input arguments, one of which is an object of classB:

classdef classA
methods
   function methodA(obj,obj_classB)
      ...
   end
end

classB does not define a method with the same name as methodA. Therefore, the following syntax causes the MATLAB runtime to search the path for a function with the same name as methodA because the second argument is an object of a dominant class. If a function with that name exists on the path, then MATLAB attempts to call this function instead of the method of classA and most likely returns a syntax error.

obj = classA(...);
methodA(obj,obj_classB)

Dot notation is stricter in its behavior. For example, this call to methodA:

obj = classA(...);
obj.methodA(obj_classB)

can call only methodA of the class of obj.

Referencing Names with Expressions—Dynamic Reference

You can reference an object's properties or methods using an expression in dot-parentheses syntax:

obj.(expression)

The expression must evaluate to a string that is the name of a property or a method. For example, the following statements are equivalent:

obj.Property1
obj.('Property1')

In this case, obj is an object of a class that defines a property called Property1. Therefore, you can pass a string 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 (see Generate Field Names from Variables for information on MATLAB structures).

As an example, suppose an object has methods corresponding to each day of the week and these methods have the same names as the days of the week (Monday, Tuesday, and so on). Also, the methods take as string input arguments, the current day of the month (i.e., the date). Now suppose you write a function in which you want to call the correct method for the current day. You can do this using 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 string. For example:

datestr(date,'dddd')

ans =

Tuesday

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

datestr(date,'dd')

ans =

11

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

obj.Tuesday('11')

Specifying Precedence

Class Precedence provides information on how you can specify the relative precedence of user-define classes.

Controlling Access to Methods

There might be situations where you want to create methods for internal computation within the class, but do not want to publish these methods as part of the public interface to the class. In these cases, you can use the Access attribute to set the access to one of the following options:

  • public — Any code having access to an object of the class can access this method (the default).

  • private — Restricts method access to the defining class, excluding subclasses. Subclasses do not inherit private methods.

  • protected — Restricts method access to the defining class and subclasses derived from the defining class. Subclasses inherit this method.

Local and nested functions inside the method files have the same access as the method. Note that local functions inside a class-definition file have private access to the class defined in the same file.

Invoking Superclass Methods in Subclass Methods

A subclass can override the implementation of a method defined in a superclass. In some cases, the subclass method might need to execute some additional code instead of completely replacing the superclass method. To do this, MATLAB classes can use a special syntax for invocation of superclass methods from a subclass implementation for the same-named method.

The syntax to call a superclass method in a subclass class uses the @ symbol:

MethodName@SuperclassName

For example, the following disp method is defined for a Stock class that is derived from an Asset class. The method first calls the Asset class disp method, passing the Stock object so that the Asset components of the Stock object can be displayed. After the Asset disp method returns, the Stock disp method displays the two Stock properties:

classdef Stock < Asset
   methods   
      function disp(s)
         disp@Asset(s) % Call base class disp method first
         fprintf(1,'Number of shares: %g\nShare price: %3.2f\n',...
         s.NumShares,s.SharePrice);
      end % disp
   end
end

See The DocStock disp Method for more information on this example.

Limitations of Use

The following restrictions apply to calling superclass methods. You can use this notation only within:

  • A method having the same name as the superclass method you are invoking

  • A class that is a subclass of the superclass whose method you are invoking

Invoking Built-In Functions

The MATLAB builtin function enables you to call the built-in version of a function that has been overloaded by a method. See subsref and subsasgn Within Class Methods — Built-In Called for an example.

Was this topic helpful?