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 Method Overriding K&B page 106-108 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 "Method Overriding K&B page 106-108" Watch "Method Overriding K&B page 106-108" New topic

Method Overriding K&B page 106-108

Peter Swiss

Joined: Mar 03, 2011
Posts: 23
One of the rules for overriding is:
The overriding method can throw narrower or fewer checked exceptions.

But here is the code in Exam watch on page 108

Why doesnt this code compile then??

Ankit Garg

Joined: Aug 03, 2008
Posts: 9466

As far as overriding is concerned, eat method in Dog2 class is throwing fewer checked exceptions isn't it. So that should compile fine. But the code is not compiling as you've written in your comment as well. Its not compiling because the compiler only knows that a variable is of type Animal which throws an Exception so you need to handle it. The compiler doesn't know that at runtime the eat method of Dog2 class will be called which doesn't throw any exception...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Alexander Sales
Ranch Hand

Joined: Feb 21, 2011
Posts: 89

static methods cannot be overriden.

Meherdad Bomanbehram
Ranch Hand

Joined: May 28, 2007
Posts: 142

Only instance methods can be overridden as it is clearly documented on page 139 of the same book.

In the example the the Animal eat() method is not static .

polymorphic invocation of happens at runtime of which the compiler knows nothing about.

Peter Swiss

Joined: Mar 03, 2011
Posts: 23
Ok, So the compiler only sees "Animal a" and since Animal class' eat() method throws an exception, the compiler expects you to either "Handle/Declare it"
But @run time, since Dog2 version is invoked, it runs fine.

Sorry for the typo brother, the method is not static!!

Yes, polymorphic invocations are done by the JVM!!
Compiler only sees "Animal a"

Thank you so much for your reply guys!!!

Appreciate your help.
I agree. Here's the link:
subject: Method Overriding K&B page 106-108
It's not a secret anymore!