wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes overriding doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "overriding doubt" Watch "overriding doubt" New topic
Author

overriding doubt

dolly shah
Ranch Hand

Joined: Jun 18, 2007
Posts: 383
This block of code & description is from K & B book, chap:2 & page:102.
I have doubt in exception declaration. It is written in the book that overriding method can throw narrower or fewer exception or no exception, those declared in overridden method. Why below code does not compile, as the overriding method declares no exception. Can anyone please explain the concept behind of this?

If a method is overridden but you use a polymorphic (supertype)
reference to refer to the subtype object with the overriding method, the compiler assumes you�re calling the supertype version of the method. If the supertype version declares a checked exception, but the overriding subtype method does not, the compiler still thinks you are calling a method that declares an exception (more in Chapter 5).
Let�s take a look at an example:

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.


SCJP-1.5<br />SCWCD-1.4
ahmed yehia
Ranch Hand

Joined: Apr 22, 2006
Posts: 424

If a method is overridden but you use a polymorphic (supertype)
reference to refer to the subtype object with the overriding method, the compiler assumes you�re calling the supertype version of the method. If the supertype version declares a checked exception, but the overriding subtype method does not, the compiler still thinks you are calling a method that declares an exception

Thats it, so to fix the code you need to handle or declare the exception.
for eg wrap the call of the method with try/catch Or make the main method throws the Exception.
[ September 27, 2007: Message edited by: Ahmed Yehia ]
Lucky J Verma
Ranch Hand

Joined: Apr 11, 2007
Posts: 278
yes this is because of polymorhism acting behind at compile time.

In polymorphic method calls ,which method can be invoked depends on the Reference type ,not run time type.Although method call itself depends on run type.

it all happens at compile time.Ploymorhism is resoled at compile time ,when compile have no informatin about runtime type or actual object type.

Since method invocations ->depends on Reference type,compile time,it throws exceptions,Compiler thinks invoked method may throw an exception
 
Don't get me started about those stupid light bulbs.
 
subject: overriding doubt