Slightly confused, the code below compiles fine (imports are not included), it defines a method throwIt() in the interface which throws a checked IO Exception, class C implements interface I and is allowed to redefine the throwIt() method without the IO Exception, why is this allowed? The InheritenceTest class is then able to implement and call the throwIt() method without having to catch the IOException. I thought if the interface defines certain behaviour then the sub classes have to honour it? Obviously it has something to do with class C redefining the interface method and dropping the throw declaration but why is this allowed?
You're allowed to throw fewer (or more specific) exceptions when you implement or override a method, because there's no danger in doing this. You're still satisfying the Liskov Substitution Principle, because you can always use an instance of the class in any situation where an instance of the interface is needed.
But allowing more (or more general) exceptions isn't allowed, because it would allow the following unsafe code:
It's very similar to return types when overriding. You can (as of Java 1.5) return a more specific type in the overriding method. But you can't return a more general type.
Joined: Aug 04, 2011
Matthew, sorry for delayed reply.
Excellent answer thank you, helped clear up the issue!!