• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Method Overriding K&B page 106-108

 
Peter Swiss
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Alexander Sales
Ranch Hand
Posts: 89
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
static methods cannot be overriden.
 
Meherdad Bomanbehram
Ranch Hand
Posts: 142
Java Netbeans IDE Ubuntu
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic