Q. What is the output for the below code?
import java.io.FileNotFoundException;
class A{
public void printName() throws FileNotFoundException{
System.out.println("Value-A");
}
}
class B extends A{
public void printName() throws NullPointerException{
System.out.println("Name-B");
}
}
public class Test{
public static void main (String[] args) throws Exception{
A a = new B();
a.printName();
}
}

  • (A) Value-A
  • (B) Compilation fails-Exception NullPointerException is not compatible with throws clause in A.printName()
  • (C) Name-B
  • (D) Name-B D. Compilation succeed but no output
πŸ’¬ Discuss
βœ… Correct Answer: (C) Name-B
Explanation: The overriding method can throw any unchecked (runtime) exception, regardless of exception thrown by overridden method. NullPointerException is RuntimeException so compiler will not complain.
Explanation by: Kiran Rapria
The overriding method can throw any unchecked (runtime) exception, regardless of exception thrown by overridden method. NullPointerException is RuntimeException so compiler will not complain.

πŸ’¬ Discussion


πŸ“Š Question Analytics

πŸ‘οΈ
133
Total Visits
πŸ“½οΈ
2 y ago
Published
πŸŽ–οΈ
Kiran Rapria
Publisher
πŸ“ˆ
99%
Success Rate