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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "overriding doubt" Watch "overriding doubt" New topic

overriding doubt

geeta vemula
Ranch Hand

Joined: Jul 18, 2008
Posts: 208
I got it from

Select three correct statements about the following code.
public class Question20 {
public static void main(String[] args) {
Question20 myref = new Question20Sub();
}catch(Exception e){}
void test() throws Exception{
System.out.println("In Question20");
throw new Exception();
class Question20Sub extends Question20 {
void test() {
System.out.println("In Question20Sub");

A. The try-catch block that encloses myref.test(); is mandatory for the code to compile.
B. Prints: In Question20
C. Prints: In Question20Sub
D. Method test() in class Question20Sub has no obligation to declare a throws clause.
E. An exception is thrown at runtime.
Ans A,C,D

My doubt is why try-catch block is mandatory because we can also declare main with throws clause.
Ans why does this code compiles, as there is no throws clause in overridding method and also Exception is the clecked Exception
Kindly clear my doubts

Geeta Vemula
Anthony Accioly

Joined: Dec 22, 2008
Posts: 16


Let's take a look at what is happening both at compiling time and running time.

At compiling time, with the code we are telling the compiler to reference a Question20Sub object by a Question20 variable, so, for the compiler, the method signature for test is . That's why either the try/catch block or something like is needed.

If we had something like
public static void main(String[] args) {
Question20Sub myref = new Question20Sub();


the code would compile because the Question20Sub test method signature don't throw any checked exceptions.

As a rule, sub class overridden methods can (but don't have to) throw any of the declared exceptions at it's super class (or sub classes of the exceptions declared at the super class). That means that it is ok for a sub class overriden method to do not declare super class exceptions, but it is not ok for it to declare broader exceptions than those declared at the super class.

When the program runs, the myRef variable in the stack actually points to a Question20Sub object in the heap, and as so, the test method prints "In Question20Sub".

I Hope that clears it out. For further reference take a look at Chapter 5 - Flow Control, Exceptions and Assertions - of Sun Certified Programmer Study Guide by Kathy Sierra and Bert Bates.


[ December 29, 2008: Message edited by: Anthony Accioly ]
[ December 29, 2008: Message edited by: Anthony Accioly ]
I agree. Here's the link: http://aspose.com/file-tools
subject: overriding doubt
It's not a secret anymore!