Get property of the parent object

28 ビュー (過去 30 日間)
Pierrick Bersier
Pierrick Bersier 2014 年 10 月 9 日
コメント済み: Captain Karnage 2023 年 1 月 13 日
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 件のコメント
Adam
Adam 2014 年 10 月 14 日
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 2014 年 10 月 14 日
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.

サインインしてコメントする。

採用された回答

Guillaume
Guillaume 2014 年 10 月 14 日
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 件のコメント
Captain Karnage
Captain Karnage 2023 年 1 月 13 日
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.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeConstruct and Work with Object Arrays についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by