Filter löschen
Filter löschen

How to override methods called in static methods?

10 Ansichten (letzte 30 Tage)
mc
mc am 12 Mai 2017
Kommentiert: mc am 19 Mai 2017
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?

Akzeptierte Antwort

Nagarjuna Manchineni
Nagarjuna Manchineni am 19 Mai 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 Kommentar
mc
mc am 19 Mai 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Software Development Tools finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by