Cannot access protected property?
9 次查看(过去 30 天)
显示 更早的评论
Hi all,
The following simple test code (in 3 separate files of course...) reproduces my problem:
classdef top_class < handle
methods
function do_something(obj, fieldname)
disp(obj.(fieldname))
end
end
end
classdef derived_class < top_class
properties (Access = protected)
P
end
end
function test
clc
close all
h = derived_class;
h.do_something('P', pi)
disp('Done')
Error:
Getting the 'P' property of the 'derived_class' class is not allowed.
Error in top_class/do_something (line 4)
disp(obj.(fieldname))
The method 'do_something()' was set up this way such that users can perform some restricted operations on protected properties in all sorts of dervied classes, while the method also does a lot of things that have to do with the top-class class itself. It is important that the P-property is protected, the user is not allowed to directly modify it.
I would expect that the above structure is not a problem since P is protected, but do_something() is inherited from top_class and therefore also a method of derived_class. Why does the error occur, and more important: how can I solve this?
Thanks in advance for thinking with me,
Jeroen
0 个评论
采纳的回答
Geoff Hayes
2015-10-28
Jeroen - I think the problem is that you are trying to access the protected member of the derived class from the base class. Look at class property attributes and consider how protected is defined as access from class or subclasses.
Generally, you can't access derived class members from the base class (though with MATLAB it seems you can if you assign access as public). Why not overload this method in the derived classes and call the base class method when needed? See calling base class methods from subclass objects for the manner in which to do this.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!