OOP in Matlab: input arguments for methods other than constructor
17 次查看(过去 30 天)
显示 更早的评论
When trying to modify object properties in the command window, it seems that the first input argument (the object name) is always omitted. Why is this the case?
Also, when I make the object name the second input argument, then I get the following error: "Attempt to reference field of non-structure array." Why does the object have to be the first input argument?
An example (straight from MathWorks documentation) is shown below, and the relevant line is the "withdraw" method. As you can see, the object is an input argument but when you use this method from the command window you say BA.withdraw(600) instead of BA.withdraw(BA,600). Why is that?
Thank you!
classdef BankAccount < handle
properties (Hidden)
AccountStatus = 'open';
end
% The following properties can be set only by class methods
properties (SetAccess = private)
AccountNumber
AccountBalance = 0;
end
% Define an event called InsufficientFunds
events
InsufficientFunds
end
methods
function BA = BankAccount(AccountNumber,InitialBalance)
BA.AccountNumber = AccountNumber;
BA.AccountBalance = InitialBalance;
% Calling a static method requires the class name
% addAccount registers the InsufficientFunds listener on this instance
AccountManager.addAccount(BA);
end
function deposit(BA,amt)
BA.AccountBalance = BA.AccountBalance + amt;
if BA.AccountBalance > 0
BA.AccountStatus = 'open';
end
end
function withdraw(BA,amt)
if (strcmp(BA.AccountStatus,'closed')&& BA.AccountBalance < 0)
disp(['Account ',num2str(BA.AccountNumber),' has been closed.'])
return
end
newbal = BA.AccountBalance - amt;
BA.AccountBalance = newbal;
% If a withdrawal results in a negative balance,
% trigger the InsufficientFunds event using notify
if newbal < 0
notify(BA,'InsufficientFunds')
end
end % withdraw
end % methods
end % classdef
0 个评论
采纳的回答
per isakson
2015-1-4
编辑:per isakson
2015-1-4
"BA.withdraw(600) instead of BA.withdraw(BA,600)."
There are two alternative ways to call a method
withdraw( BA, 600 )
and
BA.withdraw( 600 )
(remember BankAccount is a handle class).
"Why does the object have to be the first input argument?"   and   " Why is that?"   I have no better answer than: At The Mathworks they decided on that syntax. However, there is a function, why :-)
2 个评论
per isakson
2015-1-4
编辑:per isakson
2015-1-4
"If I use the first way to call the method then it turns out that the object does not have to be the first input argument."   I don't understand what you mean. There are these two ways to call a method, but only one to define it
function withdraw( BA, amt )
In the documentation they nearly always use the name obj
function withdraw( obj, amt )
and I use
function withdraw( this, amt )
(the syntax of static methods is different)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Properties 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!