Getting a value class to have some behaviors of a handle class

1 次查看(过去 30 天)
I am new to OOP in general but most of my experience is with MATLAB and I wonder if it possible to make value classes behave like handle classes.
For Example
classdef Example
properties
Prop1
end
methods
function obj = Example()
obj.Prop1=1;
end
function ()= multiply(obj,value)
obj.Prop=obj.Prop*value;
end
end
end
I know the following code will set the Prop1 value of ExpClass to 3
ExpClass=Example
ExpClass=ExpClass.multiply(3)
And I know if change the classdef line to classdef Example < handle then the following code will do the same this
ExpClass=Example
ExpClass.multiply(3)
Is there a way the get the behavior of the second example in a value class?
Thanks for the info
  2 个评论
per isakson
per isakson 2014-4-7
编辑:per isakson 2014-4-7
  • I assume that Prop and Prop1 are the "same"
  • It is confusing to call an instance of a class ExpClass. I would prefer ExpObj.
The code you present doesn't run.
NANDHINI
NANDHINI 2024-2-13
There are different attributes and values you can use to control how users interact with your objects. Setting the SetAccess attribute to private means that property values can be changed only by a method. Setting it to immutable means that they can only be set when the object is created. They cannot be changed later, even by a method.
Although there's no noticeable difference to the user between private and immutable properties, making a property immutable prevents you, the developer, from accidentally changing the value from inside a method.
You will often want different levels of access for different properties. You can have as many properties blocks as you need, each with their own attribute settings.
properties
Prop1
end
properties (SetAccess = immutable)
Prop2
end
properties (SetAccess = private)
Prop3
Prop4
end

请先登录,再进行评论。

回答(1 个)

per isakson
per isakson 2014-4-7
编辑:per isakson 2014-4-7
Value and handle classes are different and there are reasons why Matlab has both. See
With an object of a value class you must assign the result to a new variable or overwrite the old one.
.
Try
>> ve = ValueExample;
>> ve2 = ve.multiply( 7 );
>> ve.Prop
ans =
1
>> ve2.Prop
ans =
7
where
classdef ValueExample
properties
Prop
end
methods
function obj = ValueExample()
obj.Prop = 1;
end
function obj = multiply( obj, value )
obj.Prop = obj.Prop*value;
end
end
end
and
>> he = HandleExample;
>> he.multiply(7);
>> he.Prop
ans =
7
where
classdef HandleExample < handle
properties
Prop
end
methods
function obj = HandleExample()
obj.Prop = 1;
end
function multiply( obj, value )
obj.Prop = obj.Prop*value;
end
end
end

类别

Help CenterFile Exchange 中查找有关 Class File Organization 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by