Polymorphism overriding and exception handling

 

Polymorphism   overriding and exception  handling

Below  are two rules to note when overriding methods related to exception handling

Rule 1:-   if the superclass override method does not throw an exception. Subclasses override method can only throw is” unchecked exception” throwing a checked exception will lead to compile time.

Rule 2:-  if the superclass override method does throw an exception .subclass override method can only throw .sum subclass exception throwing parent exception. exception hierarchy with lead to compile-time error also there is no issue is subclass overridden is not throwing any exception.

Rule 1 example:

class Test   {

void show()   {

System.out.println(“one”);

}
}

class  Test1  extends   Test   {

void show() throws ArithmeticException   {

System.out.println(“two”);

}

public static void main(String   args[])   {

Test  t =  new Test();

t.show();

Test1  t1 =  new Test1();

t1.show();

Rule 2 example:

class Test   {

void show()  throws RuntimeException   {

System.out.println(“one”);

}
}

class  Test1  extends   Test   {

void show() throws RuntimeException   {

System.out.println(“two”);

}

public static void main(String   args[])   {

Test  t =  new Test();

t.show();

Test1  t1 =  new Test1();

t1.show();

case 3:-

overloading and abstract method :-   abstract method in an interface or abstract class are meant to be overridden in derived  concrete class other wise compile time error will be thrown.

Example:-

abstract  class Test   {

abstract   void display(); 

}

void show()  throws RuntimeException   {

System.out.println(“one”);

}
}

class  Test1  extends   Test   {

  void display();  }

void show()   {

System.out.println(“two”);

}

}

public static void main(String   args[])   {

Test1  t1 =  new Test1();

t1.show();

}
}

Example of interface:--

Interface Test_Program   {

Void  display ();    }

Abstract class    Test   {

Abstract void display ();  

void show()  throws RuntimeException   {

System.out.println(“one”);

}
}

class  Test1  implements    Test_Program   {

  void display();    {

System.out.println(“two”);

}

void show()   {

System.out.println(“three”);

}

public static void main(String   args[])   {

Test1  t1 =  new Test1();

t1.show();

t1.display();

}
}



Post a Comment

0 Comments