Originally posted by steven brown:
Why does Java enforce that a subclass can not make overriden methods any more private than its superclass' method?
Because of the substitution rule. A subclass "IS-A" specialisation of its superclass, implying that wherever you can use an instance of the superclass, you
must be able to use an instance of the subclass. Now if any of the methods in the subclass would be more private, you would no longer be able to substitute the subclass for the superclass in situations where this method is being called.
Why does the compiler not allow overriden methods where a subclass throws exceptions not found in the superclass throws clause?
For the very same reason. Code that calls the superclass method expects a certain list of exceptions. If the subclass would throw additional (checked)exceptions, it would no longer be substitutable.
For anyone reading this, I have a question along similar lines. When overridding a method in the subclass, it is not possible to change the return type. While I can understand that you cannot widen the return type - that would fall foul of the substitution rule - I do not understand why it is not possible to narrow the return type. For instance, why can't I write
Why does the JLS prohibit this, forcing me to return an Object?
- Peter
[This message has been edited by Peter den Haan (edited September 20, 2001).]