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 query about overridden method 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 "query about overridden method" Watch "query about overridden method" New topic

query about overridden method

Jose Coqueiro

Joined: Nov 15, 2008
Posts: 28
The exam watch on the page 108 says in a nutshell that if the overridding method does not declare a exception that is declared in the overridden method the code will not compile.
but I write similar code, and its working as follow:

and the output is :

could anyone explain this???

Aurelian Tutuianu
Ranch Hand

Joined: May 13, 2004
Posts: 86
You code seems right to me. I think what you read was that the overriding method should not declare an exception which was not declared before by overridden.
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper

Joined: Aug 26, 2006
Posts: 4968

Indeed. It's the overriding of a method with an exception that can cause the trouble.

-Cameron McKenzie
Mo Jay
Ranch Hand

Joined: Feb 16, 2009
Posts: 83
Sorry Jose Coqueiro but the book is correct and you are wrong.

It looks like you are modifying the code and not following what the exam watch has said exactly, if you look carefully to your main() method it looks like you throws the exception there. So if you remove the Exception in your main() method then the error will be reported by the compiler, that Exception must be caught or thrown again which is what you did exactly therefore you should not have complained why your code works. If you want to test something in the future for confirming a solution, you need to make sure to stick with the conditions.

Jose Coqueiro

Joined: Nov 15, 2008
Posts: 28 more doubt about it!!!

in the code posted earlier....

when jvm call the line


it should not print "Class1" since the method className in the Class2 does not throw the Exception...and the compiler thinks that Im calling the superclass method?

I think there is a difference between compiler vs runtime on this question.
Lucas Smith
Ranch Hand

Joined: Apr 20, 2009
Posts: 808

Compiler doesn;t know which method will be invoked. Compiler can only check if the reference type has the method.
In this case we talk about late binding.

I agree. Here's the link:
subject: query about overridden method
It's not a secret anymore!