How can I create variables / properties for an object of same type, as of the object's class in MATLAB?

1 view (last 30 days)
I am trying to build a recursive function which will help in creating a object of a custom Class, and have children of the type same as of the custom Class.
Also, I would like to create grand child of the same object and so on.
For Example, I have an object of type "ClassA" declared as "ABC" with a name "abc". I want to have to create an object of "classA" named "xyz", which will be child of "abc".
Later I want to create an object of "classA" named "child_of_xyz" which will be child of "xyz" object, and a grand child of "abc".

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 28 Sep 2020
You can define a custom Class as mentioned below:
classdef classA < handle
properties
child classA
Name
end
methods
function obj = classA(name)
obj.Name = name;
end
function obj = populateChildForThis(obj,value)
obj.child = classA(value);
end
end
end
Details of class "classA"
- Note: "classA" is derived from the handle class. Please refer to the documentation link <https://www.mathworks.com/help/matlab/matlab_oop/comparing-handle-and-value-classes.html#bu6t672 here > for more details.
- In this class there are 2 properties.
1. Name - We can store the name of the object which we can use as a reference.
2. child - This property is of the same type as of the object itself (i.e. classA). We can store the reference of the child in here.
- In this class there is one constructor we are using to assign the name to the object we are creating.
- The method "populateChildForThis" is used to create the child of the object "obj" with the name "value".
- If you want to test this class, please run the below code scripts sequentially.
>> ABC = classA("abc")
ABC = populateChildForThis(ABC,"xyz")
XYZ = ABC.child
XYZ= populateChildForThis(XYZ,"child_of_xyz")
ABC.child.child

More Answers (0)

Categories

Find more on Class Introspection and Metadata in Help Center and File Exchange

Tags

Products


Release

R2016b

Community Treasure Hunt

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

Start Hunting!