MATLAB: How does MATLAB solve the diamond problem in multiple inheritance

MATLAB

I would like to know if subclassing from 2 superclasses which in turn subclass a common "ancestor" base class poses any problems in MATLAB.

Best Answer

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:
>> dobj = D
Error 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.Amethod
B 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.