Java Reference
In-Depth Information
The Banker interface declares two methods called withdraw() and deposit() . Let's consider the following
implementation of the Banker interface in the MinimumBalanceBank class. The overridden methods in this class have
exactly the same constraints as defined in the Banker interface. Both methods are declared public and both of them
throw the same exception as declared in their declarations in the Banker interface.
public class MinimumBalanceBank implements Banker {
public double withdraw(double amount) throws InsufficientFundException {
// Code for this method goes here
}
public void deposit(double amount) throws FundLimitExceededException {
// Code for this method goes here
}
}
Let's consider the following implementation of the Banker interface in the NoLimitBank class. The NoLimitBank
has rules that a customer can have unlimited overdraft (wish it happened in reality) and there is no upper limit on the
balance. NoLimitBank has dropped the throws clause when it overrode the withdraw() and deposit() methods of the
Banker interface.
public class NoLimitBank implements Banker {
public double withdraw(double amount) {
// Code for this method goes here
}
public void deposit(double amount) {
// Code for this method goes here
}
}
The code for NoLimitBank is valid, even though its two methods that overrode the Banker interface methods
have dropped the throws clause. Dropping constraints (exceptions in this case) is allowed when a class overrides an
interface method. An exception in the throws clause imposes a restriction that the caller must handle the exception.
If you use the Banker type to write the code, here is how you will call the withdraw() method:
Banker b = get a Banker type object;
try {
double amount = b.withdraw(1000.90);
// More code goes here
}
catch (InsufficientFundException e) {
// Handle the exception here
}
At compile-time, when the b.withdraw() method is called, the compiler forces you to handle the exception
thrown from the withdraw() method because it knows the type of the variable b is Banker and the Banker type's
withdraw() method throws an InsufficientFundException . If you assign an object of NoLimitBank to the variable
b in the above code, no exception will be thrown from the withdraw() method of the NoLimitBank class when
b.withdraw() is called, even though the call to withdraw() method is inside a try-catch block. The compiler cannot
check the runtime type of variable b . Its safety check is based on the compile-time types of the variable b . It would
 
Search WWH ::




Custom Search