How could I access the object from its property in an OOP

21 ビュー (過去 30 日間)
Hadi Hajieghrary
Hadi Hajieghrary 2014 年 2 月 5 日
回答済み: Abhipsa 2025 年 6 月 5 日
Hello,
I Have define two object. On handle object,and another object is beeng passed to the handle object as its properties. Assume like a handle object of Field, which includes some Robot-objects bounded to it as its property. Now, in a method inside the Robot Class I want to access some property of the field, like its dimension. Is there any way which does not includes definning a global variable?
Thank you,
Hadi Hajieghrary

回答 (1 件)

Abhipsa
Abhipsa 2025 年 6 月 5 日
I understand that there are two classes involved:
  1. A handle class called “Field”, which contains one or more objects of another class called “Robot” as its properties.
  2. 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:
classdef Field < handle
properties
Dimension % Example property
Robots % Cell array of Robot objects
end
methods
function obj = Field(dim)
obj.Dimension = dim;
obj.Robots = {}; % initialize empty
end
function addRobot(obj, robot)
robot.ParentField = obj; % Assign this Field object to Robot
obj.Robots{end+1} = robot;
end
end
end
classdef Robot < handle
properties
ParentField % Reference to the Field object this Robot belongs to
end
methods
function obj = Robot()
% Constructor - can initialize robot-specific things here
end
function someMethod(obj)
% Access a property from the Field this robot belongs to
if ~isempty(obj.ParentField)
disp(['Field Dimension: ', mat2str(obj.ParentField.Dimension)]);
else
disp('This robot has no assigned field.');
end
end
end
end
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.

カテゴリ

Help Center および File ExchangeNumerical Integration and Differential Equations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by