Set the private property of a class without using a constructor

13 次查看(过去 30 天)
I have a class and i just need to set the private property of the class without using constructor. Is this possible? So basically its this.
Classdef NumberClass
properties (Access = private)
Number;
end
methods
function obj = set.Number(obj,value)
obj.Number = value;
end
end
end
And then I tried to do this.
num = NumberClass;
num.Number = 50;
This doesnt work. I have also tried
function obj = Set(obj,value)
obj.Number = value;
end
num.Set(50);
Here there is no error but nothing happens.
So how can I set a private property in MATLAB without using constructor. Thank you.

采纳的回答

Yash
Yash 2023-9-1
In MATLAB, if you want to set a private property in a class without using the constructor, you can create a public method within the class that allows you to set the private property. Here's how you can modify your NumberClass to achieve this:
classdef NumberClass
properties (Access = private)
Number;
end
methods
function obj = NumberClass()
% Constructor (if needed)
end
function obj = setNumber(obj, value)
% Public method to set the private property
obj.Number = value;
end
function value = getNumber(obj)
% Public method to get the private property
value = obj.Number;
end
end
end
With this modification, you can create an instance of the NumberClass and use the setNumber method to set the private property:
num = NumberClass;
num.setNumber(50);
You can also create a getNumber method to retrieve the value of the private property:
value = num.getNumber();
This way, you can encapsulate the access to the private property and provide controlled ways to set and get its value without using the constructor.
I hope this helps.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by