How to override methods called in static methods?

12 visualizzazioni (ultimi 30 giorni)
I am working on changing the functionality of a class which makes very heavy use of static methods. I would like to change some of the methods which are called by one of these static methods without having to change the original method itself. Is this even possible with the way Matlab handles static methods?
Here is a MWE. I start with a base class:
classdef ClassA
methods (Static)
function inner_method()
disp('ClassA!');
end
function outer_method()
ClassA.inner_method();
end
end
end
ClassA has a method called "outer_method" which I call when using the code, and a method called "inner_method" which gets called by "outer_method". Now, suppose I want to change what "inner_method" does, and have that change propagate into "outer_method". If this were not a static method, I could just do something like this:
classdef ClassB < ClassA
methods (Static)
function inner_method()
disp('ClassB!');
end
end
end
But, because the static method has to be hard-coded to call "ClassA.inner_method()", what actually happens is that ClassB.outer_method() still prints "ClassA!". Here's the code to use the example:
ClassA.outer_method();
ClassB.outer_method();
% Actual output:
% >> mwe
% ClassA!
% ClassA!
% Desired output:
% >> mwe
% ClassA!
% ClassB!
What is the correct way to handle this situation?

Risposta accettata

Nagarjuna Manchineni
Nagarjuna Manchineni il 19 Mag 2017
Static methods cannot be overridden like that. Always the parent class method will be executed in your case. This is because you are trying to call "ClassA.inner_method();" when you execute outer_method().
So, change your ClassB as follows (which overrides the static outer_method and calls ClassB.inner_method() instead of ClassA.inner_method())
classdef ClassB < ClassA
methods (Static)
function inner_method()
disp('ClassB!');
end
function outer_method()
ClassB.inner_method();
end
end
end
See the following documentation link for more information on Static methods:
  1 Commento
mc
mc il 19 Mag 2017
Thank you! I was afraid this was the case (and this is how I have been working around this issue so far), but wanted to see if there was some clever functionality to avoid having to duplicate outer_method() in the subclass.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Construct and Work with Object Arrays in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by