Accessing child properties from parent classes / abstract method where every child's implementation would be identical?
13 次查看(过去 30 天)
显示 更早的评论
MATLAB defines a protected property to mean accessible from the class defining the property and all child classes (but NOT any parent classes). I want to make a method that does a certain operation on each of a set of properties. The method does not explicitly reference any properties by name - it just does its work on each property of the object that matches a certain specification - e.g. on each property whose name is to be found in a list of property names (which is itself contained in a property). This method needs to be available to any of a number of different classes and its code is character-for-character identical for each class (since it doesn't explicitly name any properties). Now, I would have thought the clean way to do this would be to define the method once in a single parent class. However, if I do that, it is unable to access any properties specific to a child class that are either protected or private. The typical solution would be to define the method in the parent class only as abstract and then implement it separately in each child, but that is silly in this case because, as I said, the code is identical for all. I would literally be copying and pasting the same code 50 times, which is exactly what OOP is supposed to avoid. Any way around this or am I just up against a shortcoming of the standard OOP framework?
0 个评论
回答(1 个)
Daniel Shub
2011-9-2
You can set the GetAccess and SetAccess attributes of the proeprties to be public (you can also make the proeprties hidden so the user does not know about them). This way the superclass can access the properties. Then you can define subsref and subsasgn methods to make them effectiviely inaccessable to functions outside the class heirechy (this can probably be done in the superclass). The properties will not be truly inaccessable since the the class subsref and subsassgn methods can be bypassed (e.g., with the builtin function).
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Customize Object Display for Classes 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!