Java Reference
In-Depth Information
never be a problem if the runtime throws a fewer number of exceptions or no exceptions than expected in the code,
Consider the following implementation of the
Banker
interface by the
UnstablePredictableBank
class:
// The following code will not compile
public class UnstablePredictableBank implements Banker {
public double withdraw(double amount)
throws InsufficientFundException, ArbitraryException {
// Code for this method goes here
}
public void deposit(double amount) throws FundLimitExceededException {
// Code for this method goes here
}
}
This time, the
withdraw()
method adds a new exception,
ArbitraryException
, which adds a new constraint to
the overridden method. Adding constraints to an overridden method is never allowed.
Consider the following snippet of code:
Banker b = new UnstablePredictableBank();
try {
double amount = b.withdraw(1000.90);
// More code goes here
}
catch (InsufficientFundException e) {
// Handle exception here
}
The compiler does not know that at runtime the variable
b
, which is of type
Banker
, will refer to an
object of the
UnstablePredictableBank
type. Therefore, the compiler will force you to handle only the
InsufficientFundException
when you call
b.withdraw()
. What happens when
ArbitraryException
is thrown from
the
withdraw()
method at runtime? Your code is not ready to handle it. This is the reason that you cannot add new
exceptions to a method declaration in a class, which overrides a method in its implementing interface.
If a class overrides a method of the implemented interface, that method must be declared
public
. Recall that
all methods in an interface are implicitly
public
, and
public
is the least restricting scope modifier for a method.
Declaring a method in the class that overrides an interface method as
private
,
protected
, or package-level is like
restricting the scope of the overridden method (like placing more constraints). The following snippet of code will not
compile because the
withdraw()
and
deposit()
methods are not declared
public
:
// Code would not compile
public class UnstablePredictableBank implements Banker{
// withdraw() method must be public
private double withdraw(double amount) throws InsufficientFundException {
// Code for this method goes here
}
// deposit() method must be public
protected void deposit(double amount) throws FundLimitExceededException {
// Code for this method goes here
}
}