Superclass method calls subclass method: bug or feature? How to call same level method?

13 views (last 30 days)
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

Answers (2)

Image Analyst
Image Analyst on 17 Apr 2017

Why can't it be both?


Informaton
Informaton on 17 Apr 2017
Edited: per isakson on 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.

Categories

Find more on Construct and Work with Object Arrays in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!