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

조회 수: 3 (최근 30일)
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 CenterFile 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!

Translated by