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!