MATLAB: Passing on superclass property values to subclass

oop

Below I have a superclass called "myclass". Its constructor is written to initialize property 'a' with the 'input' argument, unless this argument is already an object of myclass, in which case it simply returns the object unchanged.
classdef myclass
properties
a=1;
end
methods
function obj=myclass(input)
if isa(input,'myclass')
obj=input; return
else
obj.a=input;
end
end
end
end
Both the following give the desired behavior,
>> objSuper=myclass(2)
objSuper =
myclass with properties:
a: 2
>> objSuper=myclass(objSuper)
objSuper =
myclass with properties:
a: 2
Now, I have a subclass called "mysubclass". Apart from intializing the superclass part of the object, the only desired behavior of its constructor is to modify the superclass property a, multiplying it by 10.
classdef mysubclass < myclass
methods
function obj=mysubclass(input)
obj=obj@myclass(input);
obj.a=10*obj.a;
end
end
end
As with the superclass, I would like the subclass constructor to be able to accept as input either a desired initializing value for 'a', or an object of type myclass itself, and use it accordingly to initialize the super-class part of the object.
The former works as I intend,
>> objSub=mysubclass(2)
objSub =
mysubclass with properties:
a: 20
The latter, however, gives me
>> objSub=mysubclass(objSuper)
When constructing an instance of class 'mysubclass', the constructor must preserve the class
of the returned object.
Error in mysubclass (line 9)
obj=obj@myclass(input);
I don't understand precisely why this error occurs. It appears that the command obj=obj@myclass(input) is somehow deleting the subclass part of 'obj', but as long as obj@myclass returns a valid object of type myclass (which it does), I don't see why the subclass constructor cannot handle that.

Best Answer

I think what Adam said here is the key:
but it knows it is creating this as part of creating the subclass
In other words, the 'obj' output of the myclass() constructor is not an ordinary output variable. Not only is it pre-initialized when the myclass workspace is entered, but the pre-initialization type also depends on how myclass() was invoked. If it was invoked using a subclass object, as in subclassObj@myclass() then obj is pre-intialized to the subclass type. This is confirmed by the following,
classdef myclass
methods
function obj=myclass
disp ' '
disp(['obj is a ' class(obj) ' object'])
disp ' '
end
end
end
classdef mysubclass < myclass
methods
function obj=mysubclass
obj=obj@myclass;
end
end
end
which gives the behavior:
>> myclass;
obj is a myclass object
>> mysubclass;
obj is a mysubclass object
And therefore, assigning obj a superclass object, even in the superclass constructor, can force it to be the wrong type.