Superclass method calls subclass method: bug or feature? How to call same level method?
Afficher commentaires plus anciens
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
Réponses (2)
Image Analyst
le 17 Avr 2017
2 votes
Why can't it be both?

Informaton
le 17 Avr 2017
Modifié(e) : per isakson
le 18 Avr 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
Catégories
En savoir plus sur Construct and Work with Object Arrays dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!