Overriding "get"-able properties.
显示 更早的评论
Let's say I have a class "A" that looks like this:
classdef A
properties (GetAccess = public, SetAccess = protected)
foo;
end
methods
function f = get.foo(self) %#ok<MANU>
f = randn(1, 1);
end
end
end
And now let's say I want to override the "foo" property in a child class that returns a uniformly random variable. In just about every other object-oriented programming language with which I am familiar, I would do the following:
classdef B < A
properties (GetAccess = public, SetAccess = protected)
foo;
end
methods
function f = get.foo(self) %#ok<MANU>
f = rand(1, 1);
end
end
end
But in MATLAB, this is not the right answer. I try this and here's the error that I see:
>> b = B
Error using B
Cannot define property 'foo' in class 'B' because the property has already been defined in the super-class 'A'.
I have tried adding the Dependent tag to the property to no avail, also, Abstract in this case will also not work because (according to the documentation), the properties in the "concrete" classes must be static (i.e., not dynamically calculated).
This is really hindering my work to create a clean design in how some of my tools work together. Can somebody please provide some insight into how to accomplish this?
Thanks!
采纳的回答
更多回答(2 个)
Andrew Newell
2012-3-6
0 个投票
The problem occurs because you have to redefine the property foo in addition to the method get.foo. In Modifying superclass properties, it says that there are two circumstances under which you can modify a superclass property:
- The value of the superclass property Abstract is true.
- The values of the superclass property SetAccess and GetAccess attributes are private.
I don't know if either of these circumstances are useful to you, but at least you know when you can do this.
Daniel Shub
2012-3-7
0 个投票
I think you can either
- change the property foo to be a method, which can then be overloaded, or
- you can overload subsref.
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!