Set the private property of a class without using a constructor

14 ビュー (過去 30 日間)
Govind Sankar Madhavan Pillai Ramachandran Nair
回答済み: Yash 2023 年 9 月 1 日
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 Center および File ExchangeConstruct 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