Get property of the parent object

21 views (last 30 days)
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
Adam
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
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.

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 14 Oct 2014
Perhaps, this is what you want to do:
classdef Parent < handle
properties (SetAccess = private)
name = '';
child = [];
end
methods
function this = Parent(name)
this.name = name;
end
function createchild(this, name)
this.child = child(name, this) %The child is now informed of his parent
end
end
classdef Child < handle
properties (SetAccess = private)
name = '';
parent = [];
end
methods (Access = ?Parent) %Only Parent is allowed to construct a child
function this = Child(name, parent)
this.name = name;
this.parent = parent;
end
end
methods
function createblock(this)
add_block('library/body', sprintf('%s/%s, parent.name, this.name));
end
end
end
  1 Comment
Captain Karnage
Captain Karnage on 13 Jan 2023
Great answer as far as logic... has a couple syntax errors though.
  • You're missing the end statment for your Parent classdef.
  • In the createchild function, the call to the Child constructor needs to be capitalized
Also, not an error, but would generate a warning... your end statements aren't all aligned with the corresponding keywords.

Sign in to comment.

More Answers (0)

Categories

Find more on Construct and Work with Object Arrays 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!