How to override methods called in static methods?
15 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
mc
el 12 de Mayo de 2017
Comentada: mc
el 19 de Mayo de 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?
0 comentarios
Respuesta aceptada
Nagarjuna Manchineni
el 19 de Mayo de 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:
Más respuestas (0)
Ver también
Categorías
Más información sobre Software Development Tools en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!