How to change the default Value of superclass property in subclass
13 次查看(过去 30 天)
显示 更早的评论
Is there any way to change the default value of a super class property in the property block of a subclass? I know I can change it in the constructor method, but the semantics of that doesn't seem right. Also making the property abstract in the super class is inconvenient because then you can't really directly instantiate the superclass. is there any solution to this?
5 个评论
Matt J
2012-10-3
Also explain what you mean by "I know I can change it in the constructor method, but the semantics of that doesn't seem right." I don't see how there could be anything semantically wrong with setting the value in the constructor. It seems like the most natural thing to do.
采纳的回答
更多回答(2 个)
Philip M
2021-6-25
Overriding a superclass property with a subclass property involes a few hurdles, but overwriting a superclass method with a subclass property is simple. This allows the superclass to define a set of defaults, and allows the subclasses to modify those defaults without requiring the subclasses to repeat the same lines of code in each constructor.
The concept in its absolute simplest form:
classdef Super
properties
CalculateMode
end
methods
function obj=Super
obj.CalculateMode=obj.CalculateModeSetting;
end
function out=CalculateModeSetting(~)
out=1;
end
end
end
classdef Sub < Super
properties
CalculateModeSetting=2
end
end
Which gives:
>> Super
ans =
Super with properties:
CalculateMode: 1
>> Sub
ans =
Sub with properties:
CalculateModeSetting: 2
CalculateMode: 2
0 个评论
Daniel Shub
2012-10-3
The only other way I can think to do this is to have the superclass constructor take an CalculateMode as an optional argument. Then the subclass constructor would pass the mode to the superclass.
0 个评论
另请参阅
类别
在 Help Center 和 File 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!