Java Reference
In-Depth Information
Suppose the code, which was written in terms of P type, gets a reference of a Q2 object as follows:
P p = new Q2();
try {
Employee emp = p.getEmp(10);
}
catch(EmpNotFoundException e) {
// Handle exception here
}
Note that the try-catch block is not prepared to handle the BadEmpIdException , which the method getEmp() of
the Q2 class may throw. This is the reason why declaration of class Q2 would not compile.
To summarize the rules of overriding, let's break down the parts of a method declaration as follows:
Name of the method
Number of parameters
Type of parameters
Order of parameters
Return type of parameters
Access level
List of checked exceptions in the throws clause
The first four parts must always be the same in the overriding and the overridden methods. Before Java 5, the
return type must be the same in the overriding and the overridden methods. From Java 5, if the return type is a
reference type, overriding a method's return type could also be a subtype (any descendant) of the return type of the
overridden method. Access level and list of exceptions in the overridden method may be thought of as its constraints.
An overriding method may relax (or even remove) the constraints of the overridden method. However, an overriding
method can never have more restrictive constraints than that of the overridden method.
the rules of overriding a method are complex. It may take you a long time to master them. all rules are directly
supported by the compiler. If you make a mistake in the source code while overriding a method, the compiler will
generate a nice (not always) error message that will give you a clue about your mistake. there is a golden rule about
method overriding that helps you avoid mistakes: “Whatever code is written using the superclass type must also work
with the subclass type.”
Tip
Accessing Overridden Method
Sometimes you may need to access the overridden method from a subclass. A subclass can use the keyword super as
a qualifier to call the overridden method of the superclass. Note that the Object class has no superclass. It is illegal to
use the keyword super in the Object class. As a programmer, you will never need to write code for the Object class
anyway as it is part of the Java class library.
Let's consider the code for the AOSuper class in Listing 16-12. It has a print() method, which prints a message on
the standard output.
 
 
Search WWH ::




Custom Search