Java Reference
In-Depth Information
myAccount.amount = new BigDecimal("-15.00");
System.out.println("New Balance: " + myAccount.amount);
}
9.
Run the program to see the output.
Account Created: FirstAccount
Balance: 10.00
New Balance: -15.00
10. Now, make both variables in the Account class private.
11. Did you notice that this created errors in the AccountManager class? If you hover over the red x,
you can see what the problem is:
The field Account.name is not visible.
The field Account.amount is not visible.
12. Because these fields are now private, they cannot be accessed from outside the Account class.
Create getter methods in the Account class to allow other classes to access their values.
public String getName(){
return this.name;
}
 
public BigDecimal getAmount(){
return this.amount;
}
13. Getter methods allow you to read the values of the variables, but still you cannot modify the values. To be
able to do this, you need to add setter methods to the Account class. A setter can be simple, for example:
public void setName(String newName){
this.name = newName;
}
Or you can add conditions to control what kinds of modifications can be made. For
example:
public void setName(String newName) {
String pattern = "^[a-zA-Z0-9]*$";
if (newName.matches(pattern)) {
this.name = newName;
}
}
In the second example, the matches() method checks to make sure the String contains only
letters and numbers without any symbols. This, or a similar pattern, might be a requirement
for an account's name. Add one of the getters for the name.
14. You need to create another setter for the amount. Remember when you directly changed the
amount to -15.00 earlier in this exercise? With a bank account, you probably rarely make a direct
modification like this, since all the banking transactions will need to be accounted as debits and
Search WWH ::




Custom Search