The most general workaround that I could come up with requires a specific design pattern, as follows.
Class A would now be defined as,
classdef A < handle
properties
x
end
methods
% Subclass needs to override this function to initialize the stored
% properties introduced by the subclass. Once complete, it needs to
% call the superclass implementation of this method.
function self = initStoredProperties(self,x,args)
self.x = x;
end
function self = A(x, varargin)
self.initStoredProperties(x,varargin);
self.myMethod();
end
function self = myMethod(self)
fprintf('I am an instance of class A with property x=%d\n',self.x);
end
end
end
and Class B as,
classdef B < A
properties
y
end
methods
% Subclass needs to override this function to initialize the stored
% properties introduced by the subclass. Once complete, it needs to
% call the superclass implementation of this method.
function self = initStoredProperties(self,x,args)
self.y = args{1};
initStoredProperties@A(self,x,args);
end
function self = B(x,y)
self@A(x,y);
% Now go ahead an override stored properties values from the
% super class
end
function self = myMethod(self)
fprintf('I am an instance of class B with properties x=%d and y=%d\n',self.x,self.y);
end
end
end
That is, all subclasses need to override initStoredProperties() and use that to set any new stored properties defined by the subclass, and then call the superclass implementation.
Store properties initialized by the superclass can be overridden after the subclass calls the superclass constructor.
This design pattern should ensure that everything is properly initialized before any methods get called. This pattern is taken from Swift .
Hope this helps someone else!