Why classes need 'InferiorClasses' to determine which method to call when multiple classes have the same method

1 次查看(过去 30 天)
Document from here .I know how to use InferiorClasses.But I don't know why I need to use InferiorClasses?
For example,there is two classes,I don't use InferiorClasses! When I use classA's methods,just use " obj_classA.MyMethod". When I use classB's methods,just use " obj_classB.MyMethod".
it's very flexible!So Why classes need 'InferiorClasses' to determine which method to call when multiple classes have the same method?
classdef classA
properties
a;
end
methods
function obj=classA(value)
obj.a=value;
end
function MyMethod (obj,obj_classB)
disp('The MyMethod of classA Called!');
end
end
end
classdef %(InferiorClasses = {?classA}) classB
properties
b;
end
methods
function obj=classB(value)
obj.b=value;
end
function MyMethod (obj,obj_classB)
disp('The MyMethod of classB is Called!');
end
end
end
obj_classA = classA(3);
obj_classB = classB(4);

采纳的回答

Steven Lord
Steven Lord 2023-7-29
There are several different reasons. The first is that not all of our users are familiar with or comfortable using the object.method syntax. A large subset of our user base prefers function(inputs) syntax, and in that syntax there are situations where you don't want the left-most object to control which class's overload of a method to be called.
One concrete example is this: plot(ax, obj) where ax is an axes object and obj is an object whose class has a plot method. Which plot method should this call? The axes object is the left-most object, but we don't want it to have to know about every object that could be plotted in it. So many graphics classes will define axes as an InferiorClass, to ensure that plot call would call their plot method rather than the plot method of axes.
Another is that sometimes the order of the input arguments matters. If A and B are two classes that each overload the minus method, how can we use B's minus to compute A-B? B.minus(A) computes B-A which is not what I want. But if A and B have the same priority, both A.minus(B) and A-B would call A's minus. In this case B would declare A as an InferiorClass to force A-B to call B's minus.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Graphics Object Properties 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by