aspose file tools*
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
Author

Method Overriding K&B page 106-108

Peter Swiss
Greenhorn

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
Sheriff

Joined: Aug 03, 2008
Posts: 9313
    
  17

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.


OCPJP 6, OCEWCD Java EE 6
Meherdad Bomanbehram
Ranch Hand

Joined: May 28, 2007
Posts: 140

Hi,
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.


Cheers
Meherdad
Peter Swiss
Greenhorn

Joined: Mar 03, 2011
Posts: 23
@Ankit,
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.

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

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

Thank you so much for your reply guys!!!

Appreciate your help.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Method Overriding K&B page 106-108