How can I modify private properties from inside a class

9 vues (au cours des 30 derniers jours)
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.

Réponse acceptée

MathWorks Support Team
MathWorks Support Team le 8 Août 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

Plus de réponses (0)

Catégories

En savoir plus sur Handle Classes dans Help Center et File Exchange

Produits


Version

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by