Main Content

Class Precedence

Use of Class Precedence

MATLAB® uses class precedence to determine which method to call when multiple classes have the same method. You can specify the relative precedence of user-defined classes with the class InferiorClasses attribute.

Why Mark Classes as Inferior

When more than one class defines methods with the same name or when classes overload functions, MATLAB determines which method or function to call based on the dominant argument. Here is how MATLAB determines the dominant argument:

  1. Determine the dominant argument based on the class of arguments.

  2. If there is a dominant argument, call the method of the dominant class.

  3. If arguments are of equal precedence, use the leftmost argument as the dominant argument.

  4. If the class of the dominant argument does not define a method with the name of the called function, call the first function on the path with that name.

InferiorClasses Attribute

Specify the relative precedence of user-defined classes using the class InferiorClasses attribute. To specify classes that are inferior to the class you are defining, assign a cell array of class matlab.metadata.Class objects to this attribute.

For example, the following classdef declares that MyClass is dominant over ClassName1 and ClassName2.

classdef (InferiorClasses = {?ClassName1,?ClassName2}) MyClass
   ...
end

The ? operator combined with a class name creates a matlab.metadata.Class object. See metaclass.

The following MATLAB classes are always inferior to classes defined using the classdef syntax and cannot be used in this list.

double, single, int64, uint64, int32, uint32, int16, uint16, int8, uint8, char, string, logical, cell, struct, and function_handle.

Dominant Class

MATLAB uses class dominance when evaluating expressions involving objects of more than one class. The dominant class determines:

  • Which class method to call when more than one class defines methods with the same names.

  • The class of arrays that are formed by combining objects of different classes, assuming MATLAB can convert the inferior objects to the dominant class.

No Attribute Inheritance

Subclasses do not inherit a superclass InferiorClasses attribute. Only classes specified in the subclass InferiorClasses attribute are inferior to subclass objects.

Related Topics