How does MATLAB solve the diamond problem in multiple inheritance?
14 次查看(过去 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!