Get property of the parent object
Show older comments
If object contain an other object from another class, how can I access to the proprieties of that object from the child object ? In other words related to the example I give, how can I use the variable saved in Parent in the child ?
My parent class:
classdef Parent < handle
properties
name = '' ;
child = {};
end
methods
function obj = Parent(name)
obj.name = name
end
function createChild(obj, name)
obj.child = child(name)
end
end
end
My child class:
classdef child < handel
properties
name = '';
end
methods
function obj = child(name)
obj.name = name;
end
function createBlock(obj)
add_block('library/body', strcat(parent.name, '/', obj.name)
end
end
end
7 Comments
Geoff Hayes
on 10 Oct 2014
Pierrick - under which circumstances would you want the child object to know about the parent and access its properties?
Pierrick Bersier
on 14 Oct 2014
Guillaume
on 14 Oct 2014
Pierrick, the problem is the child class, as you've written it has no relationship with the parent class, other than being created by it. It knows nothing about a parent. Hence, why Geoff asked you 'under which circumstances would you want the child object to know about the parent'.
Adam
on 14 Oct 2014
As you have it you could just pass the parent in as an argument, but given that all you want is the parent's name you could just as well just pass in the parent name as an argument.
From a design perspective I favour Guillaume's answer below though and have used a similar setup many times. Whether you want only parent class objects to be able to create children or a 3rd party object/function to create a child from a parent is up to you, but that is just a design question really.
Pierrick Bersier
on 14 Oct 2014
Adam
on 14 Oct 2014
That's no problem! English is my first (and only :( ) language but trying to name variables and classes and describe relationships between them in an easily understandable way is one of the biggest challenges I find in programming a system of many classes and variables!
Guillaume
on 14 Oct 2014
Parent / Child or Body / Element is perfectly fine for a name and describe the relationship appropriately. What I've shown in my answer is a classic design pattern in OOP.
Calling it encapsulation in this case seems wrong to me.
Accepted Answer
More Answers (0)
Categories
Find more on Properties 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!