Object Oriented Programming question: creating child objects and sum one property of all children and the parent
4 views (last 30 days)
Show older comments
Hi,
I'm just getting into matlab OOP and got stuck in creating child ojbects. I have a class like
classdef myClass
properties
myVar;
myNumber;
myName;
end
methods
function m = myClass(name,number,value)
m.myName = name;
m.myVar = value;
m.myNumber = number;
end
function printTotalValue(name)
disp(['Total value: ' num2str(name.myVar)]);
end
end
end
I can see the "total value" by running the commands
clear classes
a = myClass('apa',1,10);
a.printTotalValue;
I now want to create a hierarchy of objects, and whenever I call object.printTotalValue I want it to sum it's value and the value of all it's children, grand children etc. But how do I do this?
I want to index the hiearchy by myNumber, like this:
ObjNo1 (myName = "object 1"; myVar=3; myNumber=1)
.Obj11 (myName = "object 11"; myVar=1; myNumber=11)
..Obj111 (myName = "object 111"; myVar=30; myNumber=111)
..Obj112 (myName = "object 112"; myVar=15; myNumber=112)
..Obj113 (myName = "object 113"; myVar=2; myNumber=113)
.Obj2 (myName = "object 2"; myVar=1; myNumber=2)
.Obj3 (myName = "object 3"; myVar=23; myNumber=3)
..Obj31 (myName = "object 31"; myVar=6; myNumber=31)
And then I want to be able to call ObjNo113.printTotalValue and get 2 as result, ObjNo11.printTotalValue and get 1+30+15+2=48 as result, ObjNo2.printTotalValue and get 2 as result, etc...
But: *How do I create child objects like this? * *How do I get a list of all child objects and overload the printTotalValue function so it sums all the myVar's for the children objects? *
I've been googling for quite some time but can't seem to find an answer that gets me through this, so any help would be appreciated!
Thanks in advance, Anders
0 Comments
Accepted Answer
Malcolm Lidierth
on 1 Jul 2012
Edited: Malcolm Lidierth
on 1 Jul 2012
You could try something like this:
classdef myClass < hgsetget
properties
ParentObject=[];
ChildObjects={};
myVar;
myNumber;
myName;
end
methods
function thisObject = myClass(name,number,value)
thisObject.myName = name;
thisObject.myVar = value;
thisObject.myNumber = number;
end
function addChild(thisObject, newObject)
thisObject.ChildObjects{end+1}=newObject;
newObject.ParentObject=thisObject;
end
function object=getChild(thisObject, n)
object=thisObject.ChildObjects{n};
end
end
end
Then at the command line:
>> a=myClass('Eve', 1, 22);
>> a.addChild(myClass('Cain',2,99));
>> a.addChild(myClass('Abel',3,999));
>> a.getChild(1).addChild(myClass('Enoch',4,1999));
printTotalValue can then just search upwards using the ParentObject entry until it finds it empty.
More Answers (0)
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!