I've come across this problem many times, and I was hoping to solve it finally.
Context
When creating a heterogeneous class hierarchy in MATLAB, there is a protected static method called getDefaultScalarElement, which allows you to define the default scalar object for creating arrays. If an element of the hierarchy is abstract, you can override that method to use a different class.
For example
classdef (Abstract) AbstractRoot < matlab.mixin.Heterogeneous
methods (Static, Access = protected)
function DefaultObj = getDefaultScalarElement()
DefaultObj = ConcreteSubclass1();
end
end
end
classdef ConcreteSubclass1 < AbstractRoot
end
classdef ConcreteSubclass2 < AbstractRoot
end
Every concrete class in matlab has a public static hidden method called empty, which creates an empty array of that object. I would like to create an empty method for the abstract class which is similar in functionality to the getDefaultScalarObject method. This would allow me to call AbstractRoot.empty() and receive an empty array of the default kind.
For example:
classdef (Abstract) AbstractRoot < matlab.mixin.Heterogeneous
methods (Static, Hidden)
function EmptyObj = empty()
EmptyObj = ConcreteSubclass1.empty();
end
end
methods (Static, Access = protected)
function DefaultObj = getDefaultScalarElement()
DefaultObj = ConcreteSubclass1();
end
end
end
Unfortunately, this doesn't work (infinite recursion). The main problem I have is that I'm not sure how to override empty, and still be able to call the built-in version of it from the subclass, since empty is not inherited from anywhere
Questions
- Is it possible to call the built-in version of empty? If so, how?
- Is there a way of overriding empty in the abstract base class, so that subclasses will still call the built-in version of empty. Similarly, can I check which version of the static method was called (eg. 'AbstractRoot.empty' or 'ConcreteSubclass1.empty') from inside the method, so I can handle it on a case by case basis?