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

 채택된 답변

Stephen23
Stephen23 대략 2시간 전
편집: Stephen23 대략 1시간 전

0 개 추천

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.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Class File Organization에 대해 자세히 알아보기

질문:

jie
2026년 3월 18일 8:09

댓글:

jie
2026년 3월 18일 10:57

Community Treasure Hunt

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

Start Hunting!

Translated by