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.
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.
ReplyDeleteAfter 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!!
Child has no Exception
ReplyDeleteChild has no Exception