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

3 ビュー (過去 30 日間)
Istvan Horvath
Istvan Horvath 2014 年 1 月 20 日
編集済み: per isakson 2017 年 4 月 18 日
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

回答 (2 件)

Image Analyst
Image Analyst 2017 年 4 月 17 日

Why can't it be both?


Informaton
Informaton 2017 年 4 月 17 日
編集済み: per isakson 2017 年 4 月 18 日
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.

カテゴリ

Help Center および File ExchangeConstruct and Work with Object Arrays についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by