MATLAB: Access property of “superior” class (not superclass)

class propertyobjectoop

Hi all, I just wonder how to access a property of some "higher" class (object) from a "lower" class (object). Do not know how to explain clearly, so here is an example:
A = Class_higher();
B = Class_lower();
Imagine, there is a property prop_A in A, so you can access it e.g.:
A.prop_A;
Then I store B into A.prop_A:
A.prop_A = B;
Finally imagine, there is some method meth_B in B, so you can call it:
A.B.meth_B;
My question is: Is it possible to access prop_A through meth_B?
Note A is not the superclass of B…
Thanks, Adam

Best Answer

There is not really a term to describe your relationship between A and B other than to say that A has a member variable that is an instance of B.
It is of course not possible to access any private properties or methods of A from B. That is the whole tenet of encapsulation in OOP. Only the class (or derived classes) can access private members.
B can of course access any public member of A, and it can also access any member for which you give it explictly access (see the doc).
Now for an instance of B to access a member (public or one it's been granted access to) of the A instance that holds it, it needs itself to hold a reference to that A (hence A have to be a handle class). Therefore you would need:
classdef A < handle
properties (SetAccess = private, GetAccess = ?B) %B (and A of course) can read it
prop1 = 7; %property to be read by B
end
properties (SetAccess = private)
propB; %hold B instances
end
methods
function this = A() %constructor

this.propB = B(this); %pass a reference to self to B constructor
end
end
end
classdef B
properties (Access = private)
owner; an instance of A
end
methods (Access = ?A) %only A can construct B?
function this = B(Ainstance) %constructor
this.owner = Ainstance;
end
end
methods
function delete(this) %destructor. not sure it's needed.
this.owner = [];
end
function method_that_uses_A(this)
disp(this.owner.prop1)
end
end
end
Then:
a = A;
a.propB.method_that_usesA
displays
7