The Sample program given below will test your knowledge of Inheritance in Java and it will also test that how to override method properly in Java.
The Sample program given below will test your knowledge of Inheritance in Java and it will also test that how to override method properly in Java.Given below the sample code :
1 class SuperClass {
2 public void MyMethod() {
3 System.out.print("SuperClass,");
4 }}
5 class SubClass extends SuperClass {
6 public void MyMethod() throws IOException {
7 super.MyMethod();
8 System.out.print("SubClass,");
9 throw new IOException();
10 }
11 public static void main(String[] args) {
12 try {
13 new SubClass().MyMethod();
14} catch (IOException e) {
15 System.out.println("Exception");
16 }}}
How can we correct the above code ?
1. No need of correction.
2. By adding "throws IOException" at line 2(2) and(3)
Above code will give compile error because override method can't throws any exception ,which was not thrown by overridden method and to throw "IOException" you have to import "java.io" package.