MATLAB Object-Oriented Programming

(Joyce) #1
BankAccount Class Discussion
function BA = BankAccount(AccountNumber,InitialBalance)
BA.AccountNumber = AccountNumber;
BA.AccountBalance = InitialBalance;
BA.AccountListener = AccountManager.addAccount(BA);
end

Constructor initializes property values
with input arguments.

AccountManager.addAccount is static
method of AccountManager class.
Creates listener for
InsufficientFunds event and stores
listener handle in AccountListener
property.
function deposit(BA,amt)
BA.AccountBalance = BA.AccountBalance + amt;
if BA.AccountBalance > 0
BA.AccountStatus = 'open';
end
end

deposit adjusts value of
AccountBalance property.

If AccountStatus is closed and
subsequent deposit brings
AccountBalance into positive range,
then AccountStatus is reset to open.
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 newbal < 0
notify(BA,'InsufficientFunds')
end
end

Updates AccountBalance property. If
value of account balance is negative as a
result of the withdrawal, notify
triggers InsufficentFunds event.

For more information on listeners, see
“Events and Listeners Syntax” on page
11-22.

function getStatement(BA)
disp('-------------------------')
disp(['Account: ',num2str(BA.AccountNumber)])
ab = sprintf('%0.2f',BA.AccountBalance);
disp(['CurrentBalance: ',ab])
disp(['Account Status: ',BA.AccountStatus])
disp('-------------------------')
end

Display selected information about the
account.

end
methods (Static)
End of ordinary methods block.

Beginning of static methods block. See
“Static Methods” on page 9-32

3 MATLAB Classes Overview

Free download pdf