MATLAB handle class violates polymorphism on handle equivalence
Mostrar comentarios más antiguos
I am shocked to discover that MATLAB seems to violate polymorphism when it comes to equivalence of handles in handle classes.
I presume that the handle to a handle class object is synonymous to a pointer of a specific class.
E.g.
Let
classdef MyBase < handle ... end
classdef MyDerived < MyBase ... end
1. array = repmat(MyBase,1,n);
2. array(1) = MyBase; % No error
3. array(2) = MyDerived; % Error!
The assignment in line 3 should not error, as the array is of the parent of MyDerived, in accordance with the above rule of equivalence of pointers under polymorphism.
Of course, one explanation is that handles are not synonymous to pointers. And the workaround is to deploy the cell array. Not nice.
What is the official explanation to the above anomaly?
3 comentarios
JP Barnard
el 31 de Mzo. de 2011
Walter Roberson
el 31 de Mzo. de 2011
Do you find evidence in the documentation that claims that Matlab supports polymorphism of objects?
JP Barnard
el 11 de Abr. de 2011
Respuesta aceptada
Más respuestas (3)
Patrick Kalita
el 8 de Abr. de 2011
3 votos
I believe what you are looking for has been introduced in R2011a with the Heterogeneous mixin class.
3 comentarios
Andrew Newell
el 9 de Abr. de 2011
@Patrick, do you know if there would be any performance penalty for using a heterogeneous class?
JP Barnard
el 11 de Abr. de 2011
Patrick Kalita
el 11 de Abr. de 2011
@Andrew, that's a good question; I'm actually not sure what the answer is.
Andrew Newell
el 30 de Mzo. de 2011
0 votos
This is not an official explanation, but I can tell you this much: First, MATLAB does not have pointers. If you want handle polymorphism, you could try making a feature request. Another workaround for the above problem is to create a method to convert MyDerived to MyBase.
3 comentarios
Walter Roberson
el 31 de Mzo. de 2011
Editada: per isakson
el 21 de Oct. de 2016
See also this previous discussion a few months ago, in which some users said explicitly that polymorphism is not supported but discussed workarounds in the context of a particular task:
Walter Roberson
el 31 de Mzo. de 2011
In MATLAB, the type (class) of data (including objects) is not stored with the data. The type (class) is stored in a header block. MATLAB arrays have one header block for the entire array, so all elements of the array must be the exact same class unless you use a cell array. This system preserves class hierarchies but does not offer the kind of polymorphism that you would like.
Andrew Newell
el 31 de Mzo. de 2011
@Walter, where did you find that information?
JP Barnard
el 11 de Abr. de 2011
0 votos
Categorías
Más información sobre Report Generator Creation en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!