How does MATLAB solve the diamond problem in multiple inheritance?
조회 수: 17 (최근 30일)
이전 댓글 표시
MathWorks Support Team
2011년 9월 2일
편집: MathWorks Support Team
2023년 4월 27일
I would like to know if subclassing from 2 superclasses which in turn subclass a common "ancestor" base class poses any problems in MATLAB.
채택된 답변
MathWorks Support Team
2023년 4월 26일
편집: MathWorks Support Team
2023년 4월 26일
The problem you are referring to is commonly known as "the diamond problem": 2 classes B and C inherit from A and a class D inherits from both B and C; if a method in D calls a method defined in A (and does not override it), and B and C have overridden the method differently, there is an ambiguity as to which class D inherits from (B or C?). C++ solves this issue using virtual inheritance. In MATLAB, this ambiguity could arise for properties, methods and events if these are defined with the same name by the respective superclasses (i.e., B and C). The steps to be taken in order to avoid such conflicts are discussed on the following page:
For methods, and as in C++, a conflict occurs only if the superclasses (B and C) inherit a method from a common base class (ancestor A) and override it. As mentioned on the page above, one way to resolve such a conflict is to have one superclass define the method as sealed (by setting the Sealed attribute to True), in which case the subclass adopts the sealed method definition (no ambiguity). The attached example illustrates the diamond problem in MATLAB with 4 classes A, B, C and D as described above.
If you try to create a D object as follows, it results in an error:
ERROR: >> dobj = DError using D
Method 'Amethod' defined in class 'D' has 2 or more conflicting definitions.
To see how this could be resolved by defining the method as sealed in one of the superclasses, just uncomment the commented lines in B.m and run the following commands:
>> dobj = D;A constructor called
B constructor called
A constructor called
C constructor called
D constructor called
>> dobj.AmethodB version of Amethod called
Again, the diamond problem would not be there if D overrides Amethod, which could be thought of as the simplest way to resolve the conflict (though not always applicable).
In general, we recommend implementing only one unrestricted superclass and defining all methods in all other superclasses as abstract in order to save oneself the effort of resolving the potential conflicts involved when defining a subclass from multiple classes.
댓글 수: 1
Vivek Selvam
2016년 4월 21일
편집: MathWorks Support Team
2023년 4월 27일
Andy Campbell's blog is a good reference on the topic:
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Subclass Definition에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!