File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overriding doubt in K&B Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overriding doubt in K&B" Watch "Overriding doubt in K&B" New topic

Overriding doubt in K&B

Siri Naray
Ranch Hand

Joined: May 19, 2006
Posts: 105
Hello ranchers,

In K&B Rules for overriding a method - page 102 last point

"The Overriding method can throw newer or fewer exceptions.
Bottom Line: an Overriding method does'nt have to declare any exceptions that it will never throw, regardless of what the overridden medhod declares."

If this is right, why should you get a compiler error with the following code?

page 104 Exam Watch

class Animal{
public void eat() throws Exception {

class Dog2 extends Animal {
public void eat(){ // No exceptions }
public static void main(String [] args) {
Animal a = new Dog2();
Dog2 d = new Dog2();;; //compiler error- unreported exception

This code will not compile because of the Exception declared on the Animal eat() method. This happens even though, at runtime, the eat() method used would be the Dog version, which does not declare the exception.

Can anyone please explain. For be both look so contradicting.

Thank you

If you worry you cannot work... If you work you need not worry
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Variable a is a reference to an Animal, so it is Animals eat() method which is being checked for exceptions by the compiler. declares it throws Exception but you do not catch them or declare that your main method throws them.

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
abhijit Ohal
Ranch Hand

Joined: Mar 10, 2006
Posts: 64
As Overriding is done at runtime by jvm.But compiler will see the refernce variable i.e Animal class & invoke public void eat() throws Exception{} but at that time compiler Notice that exception is not handle. So it is giving exception. Definately it will call Dog2 's eat if you follow overriding rules.
Siri Naray
Ranch Hand

Joined: May 19, 2006
Posts: 105
So what should I do for this code not to generate any compiler error? Just handle the exception?
Naseem Khan
Ranch Hand

Joined: Apr 25, 2005
Posts: 809
Handle it by try/catch or put it in throws clause in main method.


Asking Smart Questions FAQ - How To Put Your Code In Code Tags
I agree. Here's the link:
subject: Overriding doubt in K&B
It's not a secret anymore!