MATLAB Answers

How do I cast a superclass object into a subclass object in MATLAB 7.7 (R2008b)?

62 views (last 30 days)
If I have a superclass object, and I would like to cast it into a subclass object. In the pre-R2008b class system I could do this:
obj_sub = class(struct(obj_super),'mySubClass');
In Java, I can do this as:
(mySubClass) obj_super
I do not see any straighforward way to do this in the current MATLAB class system.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 12 Aug 2020
Edited: MathWorks Support Team on 12 Aug 2020
MATLAB 7.7 (R2008b) does not have any functionality for directly casting a superclass object to a subclass object.
As a workaround (in any version of MATLAB), create and use a method which automatically copies over non-dependent property values:
function output = copyObject(input, output)
C = metaclass(input);
P = C.Properties;
for k = 1:length(P)
if ~P{k}.Dependent
output.(P{k}.Name) = input.(P{k}.Name);
end
end
end
For more information about converting objects of one class to another and some examples, please refer to the following documentation page:
  2 Comments
Andrew Stamps
Andrew Stamps on 29 Jan 2021
It sounds like your application would benefit from a static "factory" method in the matrix superclass. As described in the documentation, the subclass constructor can invoke the superclass constructor as needed. https://www.mathworks.com/help/matlab/matlab_oop/subclass-constructors.html
The matrix class would be as follows with a CreateObject static factory method:
classdef matrix
properties
mat
end
methods
% Constructor
function obj = matrix(mat)
% Support for zero-argument syntax
if nargin > 0
obj.mat = mat;
end
end
end
methods (Static)
function obj = CreateObject(mat)
% Factory method determines which constructor to invoke at
% runtime based on input argument.
if isvector(mat)
obj = vector(mat);
else
obj = matrix(mat);
end
end
end
end
The vector implementation is simple for now:
classdef vector < matrix
methods
function obj = vector(mat)
if nargin < 1
mat = [];
end
% Invoke superclass constructor
obj@matrix(mat);
end
end
end
Usage is as follows:
v = matrix.CreateObject(rand(5,1))
% v =
% vector with properties:
%
% mat: [5×1 double]
m = matrix.CreateObject(rand(5,5))
% m =
% matrix with properties:
%
% mat: [5×5 double]
In order to force users to use the factory method instead of invoking the constructors directly, you can make access to the matrix constructor protected and grant access to the vector constructor only to the superclass (i.e. matrix).

Sign in to comment.

More Answers (1)

Andreas Schneider
Andreas Schneider on 2 Jun 2021
Is there some nicer code for a newer version of Matlab?
(esp. if the objects are matlab.mixin.Copyable)

Community Treasure Hunt

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

Start Hunting!