MATLAB Answers

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

60 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 10 Jul 2020
Edited: MathWorks Support Team on 10 Jul 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:

  1 Comment

Benjamin D'Anjou
Benjamin D'Anjou on 31 May 2019
Very nice, but is there a way to use this in the constructor of a superclass? For instance, I would like to do something conceptually like:
classdef matrix
properties
mat;
end
methods
% Constructor
function obj = matrix(mat)
obj.mat = mat;
% If the input is a vector, construct the subclass. This doesn't work.
if isvector(obj.mat)
subObj = vector();
subObj = obj.copyObject(subObj);
obj = subObj;
end
end
end
methods
% Method to copy object
function output = copyObject(obj, output)
C = metaclass(obj);
P = C.Properties;
for k = 1:length(P)
if ~P{k}.Dependent
output.(P{k}.Name) = obj.(P{k}.Name);
end
end
end
end
end
classdef vector < matrix
methods
function vector()
end
end
end
This doesn't work, I think because of recursion issues. The constructor of "matrix" calls on the constructor of "vector", which in turn goes back to "matrix", etc. The error message is:
a = matrix([1,2,3,4]);
%Not enough input arguments.
%Error in matrix (line 10)
% obj.mat = mat;
%Error in vector (line 5)
% function obj = vector()
%Error in matrix (line 12)
% subObj = vector();
But is it possible to ask the superclass to create an instance of its subclass instead if the properties actually define a member of the subclass?

Sign in to comment.

More Answers (0)


Translated by