0

This is in continuation of question in link: I am learning the Exception handling in java (basically in inheritance) that child class method must throw the exception which is subclass of parent class method.

"When a subclass overrides a method in super class then subclass method definition can only specify all or subset of exceptions classes in the throws clause of the parent class method(or overridden method"

This is a rule. but i am not able to figure out whats the reason behind making this rule, Why vice versa is not allowed. Why this rule is created

Community
  • 1
  • 1
user3363969
  • 233
  • 1
  • 4
  • 15
  • 3
    Already answered by Steve McLeod in the previous question: http://stackoverflow.com/a/3520613/685806 – Pino Sep 08 '14 at 14:59
  • This question is not answered, the answer above explains the rule but not the reason for the rule which is what OP is asking for. – Ross Drew Sep 08 '14 at 15:06

1 Answers1

1

For polymorphism to work, the method signatures need to remain the same where expected so that they conform to the same interface.

For example if you have a Car which has a method drive() which throws UnknownIgnitionException and you have a Ford that extends that class, you will sometimes want to treat it like a car (and not specifically a Ford type Car) so you would expect the method drive() to look and act exactly the same in all cars.

This means if you wanted to test drive a bunch of cars (Ford, Fiat, Porche) you could have

 for (Car c : listOfCars) //list contains Fords, Porches, Fiats, etc
 {
   try {
      c.drive(); //All sub-classed Cars contain this exact method 
   }
   catch (UnknownIgnitionException e)
   {
   //As all subclassed cars are restricted to the same method signature, you can be sure what exceptions all Cars throw
   }
 }

If they all threw standalone exceptions then you couldn't do this.

Ross Drew
  • 8,163
  • 2
  • 41
  • 53