Java Reference
In-Depth Information
deposit() methods to change the amount. Since these can throw exceptions, make sure you use a
try-catch block to handle invalid values. Your AccountManager class might look like this:
public class AccountManager {
 
public static void main(String[] args) {
Account myAccount = new Account("FirstAccount","10.00");
System.out.println("Account Created: " + myAccount.getName());
System.out.println("Balance: " + myAccount.getAmount());
 
try {
myAccount.withdraw("20.00");
} catch (IllegalArgumentException e) {
System.out.println("Invalid Withdrawal");
} finally {
System.out.println("New Balance: " + myAccount.getAmount());
}
}
}
How It Works
Here's how it works:
1.
In the first part of the exercise, the variables in the Account class were public. This allowed you to
read and change them from the AccountManager class.
2.
Because the variables were public, they could be modified by any class without any checks or vali-
dations. Therefore, you were encouraged to change the variables to private, following the principle
of information hiding.
3.
After the variables were private, they could no longer be accessed by other classes for reading or
writing. You noticed this when the errors appeared in your AccountManager class.
4.
You created public getter methods for each of the variables in the Account class. This allows other
classes to read their values, without being able to modify them.
5.
Next, you created setter methods to modify the values of the variables in the Account class. Some
were public and some were private.
6.
By making private setter methods, you can still restrict the modifications to the same class. The
benefit of using a setter in this case, rather than directly modifying the variable, is that you can add
validations to the method to make sure the changes are allowed. For example, you might want to
prevent an account's balance from being set to a negative value. Generally these conditions will be
checked with if statements. If the provided parameter is not acceptable, you can handle it in sev-
eral ways. You might throw an exception when an invalid value is provided. You could also simply
exit the method without modifying the variable. Finally, you might modify the variable but in a
valid way. For example, if a String begins with white space, and this is not allowed, you could still
use the part of the String after the white space.
7.
By making public (or other non‐private access modifiers) setter methods, you allow them to be
called from any other class. You can still control what changes are allowed with the same types of
validations mentioned for private setter methods.
Search WWH ::




Custom Search