MATLAB: Can I Dynamically Overload A Class Method

MATLABmatlab functionoop

Hi All,
Context: I'm attempting to overload a method of class without touching the class definition or explicitly declaring a subclass.
Question: Is it possible to dynamically overload a class method either by directly overloading, dynamically creating a subclass, or intercepting method calls?
Prior Work:
The odd error message produced by the following example gives me a dim hope that its possible directly . . .
Here's an example class
classdef Hello
methods
function sayHi(obj)
fprintf('Hi\n')
end
end
end
I then attempt to dynamically override the sayHi function, producing an error as follows:
helloObj = Hello;
sayHola = @(obj) fprintf('Hola\n')
helloObj.sayHi = sayHola;
Assignment not supported because the result of method 'sayHi' is a temporary value.
Is there a way to make "sayHi" produce a non temporary value? Or is that saying that @helloObj.sayHi is itself a temporary value?

Best Answer

A class function cannot be dynamically overloaded without creating subclass. The class protects its methods from getting modified or overloaded from outside as that changes the class definition.
In the given code,
helloObj = Hello;
sayHola = @(obj) fprintf('Hola\n')
helloObj.sayHi = sayHola;
HelloObj.sayHi is a temporary value as it is just an instance of the class and was not defined in the class declaration and thus it gets its own temporary copy of all properties and cannot overload its class functions.