I understand that there are two classes involved:
- A handle class called “Field”, which contains one or more objects of another class called “Robot” as its properties.
- A class "Robot" that needs, inside one of its methods, to access a property of the “Field” object that contains it.
The query is if there exists a way for a “Robot” object to access the properties of its containing “Field” object from within a method, without using global variables.
You can access properties of the “Field” object from within a method of the “Robot” class without using global variables. The common and clean approach is to have a reference or handle to the “Field” object stored inside each “Robot” object. This way, each “Robot” knows which “Field” it belongs to, and can access the Field’s properties directly.
You can refer to the below code snippet for further reference:
function obj = Field(dim)
function addRobot(obj, robot)
obj.Robots{end+1} = robot;
if ~isempty(obj.ParentField)
disp(['Field Dimension: ', mat2str(obj.ParentField.Dimension)]);
disp('This robot has no assigned field.');
In the above code snippet:
- “Field” holds many “Robot” objects in its “Robots” property.
- Each “Robot” holds a reference to its parent “Field” in “ParentField”.
This is a classic bidirectional association in object-oriented design which is useful when a "child" object (Robot) needs to query its "Parent" (Field), like checking field dimensions.
You can refer to the below MATLAB documentations for more details:
I hope this helps you.