10
I've got two new-style MATLAB classes - B & C, both concrete subclasses of an abstract parent, A. A is a subclass of hgsetset (handle class). I'd like to put them in an array in MATLAB, and treat them both as As. They are defined, roughly, as:
classdef A <hgsetget
methods
function foo(this)
%does some common stuff, then
this.fooWorker;
end
end %public Methods
methods(Abstract, Access=protected)
fooWorker(this);
end %abstract Methods;
end
classdef B < A
methods(Access=protected)
function fooWorker(this)
%implementation
end
end %protected Methods;
end
However if I do this:
arr = [b c]; % where b & c are objects of type B & C respectively.
arr(1).foo;
arr(2).foo;
MATLAB will tell me both are of type B, and if I call the abstract method from A that both implement (foo), it executes, essentially, two copies of b.
However, if I reverse the order:
arr = [c b];
It tells me that both are of type C, and if I try to execute foo on both, it executes, essentially two copies of c.
Any ideas how to use subclasses in a polymorphic way?
I know that I can put them in a cell array and get 90% of what I need. But that is a bit of a kludge.