Java Reference
In-Depth Information
public class Q extends P {
public Employee getEmp() {
// code goes here
}
}
public class R extends P {
public Manager getEmp() {
// code goes here
}
}
Class
P
defines a
getEmp()
method that returns an object of
Employee
type. The
getEmp()
method of Class
Q
overrides the
getEmp()
method of its superclass
P
because it has the same name, number of parameters (zero in this
case) of the same type in the same order, and the same return type,
Employee
. The
getEmp()
method of class
R
also
overrides the
getEmp()
method of class
P
even though its return type
Manager
is different from the return type of the
overridden method, which is
Employee
. The
getEmp()
method of class
R
overrides its superclass
getEmp()
method
because an instance of
Manager
type can always be assigned to a variable of
Employee
type without any typecast.
Method Overriding Rule #5
The access level of the overriding method must be at least the same or more relaxed than that of the overridden
method. The three access levels are
public
,
protected
and package-level that allow for inheritance. Recall that
private
members are not inherited and hence cannot be overridden. The order of access level from the most
relaxed to the strictest is
public
,
protected
, and package-level. If the overridden method has
public
access level,
the overriding method must have the
public
access level because
public
is the most relaxed access level. If the
overridden method has
protected
access level, the overriding method may have
public
or
protected
access level.
If the overridden method has package-level access, the overriding method may have
public
,
protected
, or package-
level access. Table
16-1
summarizes this rule. I will discuss why this rule exists shortly.
Table 16-1.
List of Allowed Access Levels for an Overriding Method
Overridden Method Access Level
Allowed Overriding Method Access Level
public
public
protected
public, protected
package-level
public, protected, package-level
Method Overriding Rule #6
A method may include a list of checked exceptions in its throws clause. Although it is allowed to include an unchecked
exception in the
throws
clause of a method, it is not required. In this section, I am discussing only checked exceptions.
The overriding method cannot add a new exception to the list of exceptions in the overridden method. It may remove
one or all exceptions or it may replace an exception with another exception, which is one of the descendants of the
exception listed in the overridden method. Let's consider the following class definitions:
public class G {
public void m1() throws CheckedException1, CheckedException2 {
// Code goes here
}
}