Method lookup in multiple inheritance

I defined four classes: a, b, c, and d. Class a defines a method f; class b inherits from a and overrides f; class c inherits from a; class d inherits from both b and c.
Why does calling f(d) print 'b'? What is MATLAB's method lookup mechanism?
classdef a
methods
function f(obj)
'a'
end
end
end
classdef b < a
methods
function f(obj)
'b'
end
end
end
classdef c < a
methods
end
end
classdef d < a
methods
end
end

 Akzeptierte Antwort

Stephen23
Stephen23 vor etwa 21 Stunden
Bearbeitet: Stephen23 vor etwa 20 Stunden

0 Stimmen

f(d)
ans = 'b'
class(d)
ans = 'd'
Compare:
classdef d < a % what you wrote in your question.
classdef d < b & c % what the file actually contains
Lets check it right now:
type d.m
classdef d < b & c methods end end
This inheritance changes everything.
The Inheritance Hierarchy
a
/ \
b c
\ /
d
This is the classic diamond inheritance pattern. Both b and c inherit from a, and d inherits from both.
Why b.f() Wins
Given the following class hierarchy:
classdef a; % defines f(), returns 'a'
classdef b < a; % overrides f(), returns 'b'
classdef c < a; % does not override f()
classdef d < b & c; % does not override f()
This forms a classic diamond inheritance pattern, where a is the common base. Calling f(d) on a fresh workspace returns 'b'.
The reason is that b is the only class in the hierarchy that overrides f(). Since c does not override f(), there is effectively only one non-trivial definition of f() in the hierarchy — that of b. MATLAB resolves this unambiguously to b.f(), without requiring d to explicitly disambiguate.
This is consistent with the MathWorks documentation on Method Conflicts, which states that a conflict requiring explicit resolution arises only when multiple superclasses each provide differing definitions of the same method. Inheriting an unoverridden method from a common base (c inheriting a.f unchanged) does not constitute a distinct definition, so no conflict is raised.
However, the precise dispatch rule that b.f() is chosen rather than a.f() does not appear to be explicitly documented by MathWorks. This behavior appears to be implementation-defined.

Weitere Antworten (0)

Kategorien

Mehr zu Class File Organization finden Sie in Hilfe-Center und File Exchange

Gefragt:

jie
am 18 Mär. 2026 um 8:09

Kommentiert:

jie
am 18 Mär. 2026 um 10:57

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by