How to override methods called in static methods?
11 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
Nagarjuna Manchineni
2017 年 5 月 19 日
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:
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Construct and Work with Object Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!