Superclass method calls subclass method: bug or feature? How to call same level method?
Mostra commenti meno recenti
Hi,
I have two classes, B inherited from A, with an overloaded function Init(), defined as follows:
A.m:
classdef A
methods
function obj = A()
disp('A.Constructor()');
obj = obj.Init();
end
function obj = Init(obj)
disp('A.Init()');
end
end
end
B.m:
classdef B < A
methods
function obj = B()
disp('B.Constructor()');
obj = obj.Init();
end
function obj = Init(obj)
disp('B.Init()');
end
end
end
If I instantiate B, the display is as follows:
A.Constructor()
B.Init()
B.Constructor()
B.Init()
Which means, that the superclass constructor called the subclass' Init() function. Is this a bug or a feature? If I want the superclass call it's own Init() function, what can I do? I cannot write Init@A, it returns an error, that A is not a superclass of A, which is true.
Thanks, Istvan
Risposte (2)
Image Analyst
il 17 Apr 2017
2 voti
Why can't it be both?

Informaton
il 17 Apr 2017
Modificato: per isakson
il 18 Apr 2017
I think this is normal behavior, as sometimes you want to call the superclass init method (like here), but in other case you may not want to.
To get the behavior you want in this example, change your B.m file to the following:
classdef B < A
methods
function obj = B()
disp('B.Constructor()');
end
function obj = Init(obj)
Init@A(obj);
disp('B.Init()');
end
end
end
Instantiating B now produces the following:
A.Constructor()
A.Init()
B.Init()
B.Constructor()
You do not need to call obj.Init() in B's constructor, since you already call it obj.Init() in its superclass constructor (i.e. in A.m), which is invoked automatically prior to the subclass constructor finishing as shown in your example instantiation.
Here is a link that describes how to do this: https://www.mathworks.com/help/matlab/matlab_oop/calling-superclass-methods-on-subclass-objects.html
Categorie
Scopri di più su Construct and Work with Object Arrays in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!