Wednesday, April 22, 2009

Puzzle 18 – Exceptional Performance

Language – Java/C++ | Type – Concept | Last date 26-Apr-2009 12:00 p.m. IST | Points 2

Here is another simple Puzzle – what will be the output of this code? Looks simple? But looks can be deceiving ...

package com.twisters;
class Base {
public void test() throws Exception {
System.out.println(
"Base Exception");
throw new Exception("Base Exception");
}
}

public class Child extends Base{
public void test() {
System.out.println(
"Child has no Exception");
}

public static void main(String [] args) {
Base base
= new Child();
base.test();

Child child
= new Child ();
child.test();
}
}

Got an answer? Why don’t you leave it here.

2 comments:

  1. First you will have to handle the exception that the signature of method test() from Base object throws, as it won't compile unless you use a try/catch or declare that the function main from main throws Exception.

    After you have done it, as you declare object base as a new Child object, it will call the Child test() method instead of the parents'.

    So, the output will be:
    Child has no Exception
    Child has no Exception

    Cheers!!

    ReplyDelete
  2. Child has no Exception
    Child has no Exception

    ReplyDelete

Solution for this question?