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 endend
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 classof 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