posted 9 years ago
You're right that it's similar. In fact, the rules are as they are for exactly much the same reason. In each case, they're the only way the compiler can enforce the rules correctly. Consider this bit of code:
So, what are the restrictions on XXX and YYY? And why? Now consider this:
As far as the compiler is concerned, obj is a Superclass. So the method returns a SomeType, and throws a SomeException. So that's fine - that will compile OK. But at runtime, obj is a Subclass object. Which means:
- We're assigning an XXX value to a SomeType value.
- We might be throwing a YYY exception. If this is checked, it must be handled by the try/catch block.
The only way we can satisfy these is if XXX is SomeType or a subclass. And YYY can't include any checked exceptions that aren't SomeException or a subclass.
These rules are both related to the Liskov Substitution Principle: an instance of a class must always be replaceable by an instance of a subclass.