MATLAB Answers

Dependent property for subclasses

7 views (last 30 days)
Ste Vo
Ste Vo on 9 Mar 2021
Answered: Steven Lord on 12 Mar 2021
Why does the following inheritance not work?
class A < handle
properties (Dependent)
a
end
methods
function this = A(a)
this.a = a;
end
function a = get.a(this)
a = this.a;
end
end
class B < A
methods
function this = B(a)
this.a = a;
end
function a = get.a(this)
a = this.a+1;
end
end
The error is:
The method get.a does not refer to a valid property name

Answers (2)

Sai Veeramachaneni
Sai Veeramachaneni on 12 Mar 2021
Hi,
get.a is not a valid function name, Valid function names begin with an alphabetic character, and can contain letters, numbers, or underscore only
Try changing it to getA instead of get.a
Hope it helps.
  1 Comment
Steven Lord
Steven Lord on 12 Mar 2021
The first paragraph of your answer is true, but that syntax is valid in MATLAB. It is used to define a property accessor method for the a property. See this documentation page for more information.

Sign in to comment.


Steven Lord
Steven Lord on 12 Mar 2021
You are only allowed to define a property accessor method for a property if
  • the class in which the method is defined also defines the property
  • the class does not include a properties block that defines that property but does allow dynamic properties (see the Set and Get Methods for Dynamic Properties documentation page linked in the See Also section), or
  • the property is Abstract in its defining class, in which case a concrete subclass can define a property accessor method
See the "Restriction on Access Methods" section on this documentation page for more information.
No, a superclass defining a property in its properties block does not allow its subclasses to define a property accessor method. Doing so could allow the subclass to accept a value that would make the subclass instance not a valid superclass instance.
Consider a hierarchy where EquilateralTriangle inherits from Triangle. Triangle defines a property numSides and validates that this property always has value 3. [Yes, it should be a Constant property and not have a property accessor method, but this is a simplified example to illustrate a point.] If EquilateralTriangle could define a property accessor method that allows numSides to be 4 (due to a bug in the method) and you created an EquilateralTriangle with numSides equal to 4, it would not be a valid Triangle.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!