Class method calls method of other instantiated class

2 views (last 30 days)
Hello everyone,
I'm new to OOP and have a question.
I have the following class:
classdef Operator
properties
id;
offer;
end
methods
% Functions
function submitOffer(obj)
% submit offer
centralMarket.enterOffer(obj.offer);
end
end
An instance of this class shall pass the variable "offer" to an instance of the class "CentralMarket".
classdef CentralMarket
properties
id;
orderBook;
marketResult;
end
% Functions
function obj = enterOffer(obj, offer)
% write offer into the order book
w_idx = length(obj.orderBook) + 1;
obj.orderBook{w_idx} = offer;
end
For this I call the function "submitOffer" of the initialized class "Operator":
operator.submitOffer();
But it's not working out the way I want it to. I get the following message:
Undefined variable "centralMarket" or class "centralMarket.enterOffer".
Of course, I can work around the whole thing as follows:
centralMarket = centralMarket.enterOffer(operator.offer);
But that wouldn't be pleasant. Is there a way?

Accepted Answer

Steven Lord
Steven Lord on 11 Mar 2019
If the object stored in the offer property of the Operator class is a CentralMarket object, this should work.
function submitOffer(obj)
enterOffer(obj.offer);
end
If it is not a CentralMarket object, but the enterOffer method of the CentralMarket object were a Static method, that could work.
classdef CentralMarket
% ...
methods(Static)
function obj = enterOffer(obj, offer)
% ...
end
end
end
But because enterOffer manipulates properties of the obj object passed into it as input, it's probably not suitable to be a Static method.
You might want to read through the BankAccount and AccountManager classes on this documentation page. You may be able to use them as a model for your application. Alternately, explain in more detail (in words not code) how you want the Operator class method submitOffer and the CentralMarker class to interact with one another and we may be able to help you figure out the best way to implement that interaction.
  1 Comment
Nico Lehmann
Nico Lehmann on 18 Mar 2019
Thank you very much for the quick answer!
As you already said, the objects localMarket and centralMarket must be passed to the instance of the class "Operator" operator. It is important that both objects are handle classes so that no copies are made. Your linked tutorial with the bank account helped a lot here.

Sign in to comment.

More Answers (0)

Categories

Find more on Construct and Work with Object Arrays in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!