Java Reference
In-Depth Information
If a class overrides
m1()
method of class
G
, it must not add any new checked exception to it. The following code
will not compile, because it has added a new checked exception
CheckException3
in the overridden method
m1()
:
public class H extends G {
public void m1() throws CheckedException1, CheckedException2, CheckedException3 {
// Code goes here
}
}
The following class declarations override the
m1()
method in class
G
and they are all valid. In class
I
, the
method
m1()
removes both exceptions. In class
J
, it removes one exception and keeps one. In class
K
, it keeps one
and replaces the other one with a descendant type assuming that the
CheckedException22
is a descendant class of
CheckedException2
.
public class I extends G {
// m1() removes all exceptions
public void m1() throws {
// Code goes here
}
}
public class J extends G {
// m1() removes one exception and keeps one
public void m1() throws CheckedException1 {
// Code goes here
}
}
public class J extends G {
// m1() removes keep one and replaces one with a subclass
public void m1() throws CheckedException1, CheckedException22 {
// Code goes here
}
}
The rules about the return type and the list of exceptions of an overriding method may not be obvious. I will
discuss the reasons behind these rules. There is a reason behind these rules, which is “A variable of a class type can
hold the reference of an object of any of its descendants.” When you write code using the superclass type, that code
must also work without any modification with objects of subclass types. Let's consider the following definition of class
P
assuming the
EmpNotFoundException
is a checked exception class:
public class P {
public Employee getEmp(int empId) throws EmpNotFoundException {
// code goes here
}
}