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.
댓글 수: 0
채택된 답변
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Construct and Work with Object Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!