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

2 views (last 30 days)
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 Comments
per isakson
per isakson on 7 Apr 2014
Edited: per isakson on 7 Apr 2014
  • 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 on 13 Feb 2024
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

Sign in to comment.

Answers (1)

per isakson
per isakson on 7 Apr 2014
Edited: per isakson on 7 Apr 2014
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

Categories

Find more on Properties 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!