Java Reference
In-Depth Information
The modified version of the Account class is not acceptable in this form because you can create an account, but
you cannot read or manipulate its balance. The Account class must provide some interface for the outside world to
access and manipulate its balance in a controlled way. For example, if you have money and want to share it with the
outside world, you do not show the money to everyone and ask him to take it directly. Rather, anyone who wants your
money needs to ask you (send you a message), and then you give him your money according to certain situations. In
other words, money is your private possession and you let other access it in a controlled way by making them ask you
for that money, instead of letting them just take money directly from your pocket. Similarly, you want others to view
the balance of an account, credit money to an account, and debit money from an account. However, all these actions
should happen through an Account object, rather than manipulating the balance of an account object directly.
Java lets you send a message to an object by using instance methods. An object can receive a message from the
outside world and it can respond differently to the same message depending on its internal state. For example, when
all your money is gone and someone asks you for money, you can respond by saying that you do not have any money.
However, you responded to the same message (give me money) differently (by giving the money) when you had money.
Let's declare three public methods in the Account class that will serve as an interface to the outside world who
wants to access and manipulate the balance of an account.
A
getBalance() method will return the balance of an account.
A
credit() method will deposit a specified amount to an account.
A
debit() method will withdraw a specified amount from an account.
Both
credit() and debit() methods will return 1 if the transaction is successful and -1 if the
transaction fails.
Listing 6-19 has the code for the modified Account class.
Listing 6-19. A Modified Version of the Account Class with a Private Instance Variable and Public Methods
// Account.java
package com.jdojo.cls;
public class Account {
private double balance;
public double getBalance() {
// Return the balance of this account
return this.balance;
}
public int credit(double amount) {
// Make sure credit amount is not negative, NaN or infinity
if (amount < 0.0 || Double.isNaN(amount) || Double.isInfinite(amount)) {
System.out.println("Invalid credit amount: " + amount);
return -1;
}
// Credit the amount
System.out.println("Crediting amount: " + amount);
this.balance = this.balance + amount;
return 1;
}
 
Search WWH ::




Custom Search