OOP in Matlab: input arguments for methods other than constructor
Mostrar comentarios más antiguos
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
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Properties en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!