Reset method being called twice during instantiation of a class instance with inheritance
2 次查看(过去 30 天)
显示 更早的评论
I'm defining various classes with an inheritance hierarchy and having problems setting up each class's reset method so that it is only called once during instantiation. Here is a toy-example which illustrates the problem.
MySuperClass.m
classdef MySuperClass < matlab.mixin.Copyable
properties
a0
a
end
methods
function obj = MySuperClass(a0)
obj.a0 = a0;
obj.reset()
end
function reset(obj)
disp(" MySuperClass reset()") % for debugging
obj.a = obj.a0;
end
end
end
MyClass.m
classdef MyClass < MySuperClass
properties
b0
b
end
methods
function obj = MyClass(a0, b0)
obj = obj@MySuperClass(a0);
obj.b0 = b0;
obj.reset()
end
function reset(obj)
reset@MySuperClass(obj);
disp(" MyClass reset()") % for debugging
obj.b = obj.b0;
end
end
end
The reason I want to call the reset method during instantiation is that the reset operations are quite extensive in the actual implementation and therefore I don't want to duplicate the code in two places or have it run twice.
Test script:
% Test class instantiation
disp("1. Instantiate MySuperClass")
x1 = MySuperClass(0.1); assert(x1.a == 0.1);
x1.a = x1.a + 1;
disp("2. Reset MySuperClass")
x1.reset(); assert(x1.a == 0.1);
disp("3. Instantiate MyClass")
x2 = MyClass(0.1, 0.2); assert(isequal([x2.a x2.b], [0.1 0.2]));
x2.a = x2.a + 1;
x2.b = x2.b + 1;
disp("4. Reset MyClass")
x2.reset(); assert(isequal([x2.a x2.b], [0.1 0.2]));
This executes without errors but it is evident that the reset methods are called twice when instantiating MyClass as shown in the output after '3. Instantiate MyClass' below:
Test script output:
1. Instantiate MySuperClass
MySuperClass reset()
2. Reset MySuperClass
MySuperClass reset()
3. Instantiate MyClass
MySuperClass reset()
MyClass reset()
MySuperClass reset()
MyClass reset()
4. Reset MyClass
MySuperClass reset()
MyClass reset()
I think this is happening because the two lines obj = obj@MySuperClass(a0) and obj.reset() in MyClass.m are both calling reset@MyClass rather than the local methods.
What is the correct way to define these two classes so the reset methods are only called once when an object is instantiated?
0 个评论
回答(1 个)
Ishan Gupta
2022-7-27
Calling obj.reset() in the constructor of MyClass is redundant.
This is because while calling obj@MySuperClass(a0); you also call obj.reset() in the superclass constructor here the reset method is already overridden hence reset of MyClass.
In summary obj@MySuperClass(a0); and obj.reset() in MyClass constructor are calling the same reset function of MyClass.
Solution : eliminate obj.reset()
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Methods 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!