Set the private property of a class without using a constructor

13 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Yash
Yash il 1 Set 2023
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.

Più risposte (0)

Categorie

Scopri di più su Construct and Work with Object Arrays in Help Center e File Exchange

Prodotti


Release

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by