How can I modify private properties from inside a class
9 views (last 30 days)
Show older comments
MathWorks Support Team
on 8 Aug 2017
Answered: MathWorks Support Team
on 8 Aug 2017
Is it possible for me to modify a private property from inside a class? When I call a public method to change a private property, the property appears to not actually be changed. No errors are returned.
Accepted Answer
MathWorks Support Team
on 8 Aug 2017
The default MATLAB class is a 'value' class. If you call a method that changes a property of a 'value' class object, the operation will return a new object with the modification. However the original object will remain unchanged unless reassigned. To avoid this, inherit from the 'handle' class instead. For more information about the difference between 'value' and handle classes, see the following documentation link:
https://www.mathworks.com/help/matlab/matlab_oop/comparing-handle-and-value-classes.html
The following code will give an example of using a public method to change a private property:
classdef CTester < handle
properties (Access = private)
expectedResult = [];
end
methods
function setExpectedResult(obj,In)
obj.expectedResult = In;
end
function y = getExpectedResult(obj)
y = obj.expectedResult;
end
end
end
Now try running to check that it works:
>> tester = CTester;
>> tester.setExpectedResult(2.87);
>> tester.getExpectedResult
0 Comments
More Answers (0)
See Also
Categories
Find more on Handle Classes in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!