How can I modify private properties from inside a class

9 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 8 de Ag. de 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

Más respuestas (0)

Categorías

Más información sobre Handle Classes en Help Center y File Exchange.

Productos


Versión

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by