The following is an excerpt from the book 'The Java FAQ' .. "An API (application programming interface) establishes a contract of intent, not just of form or interpretation. To borrow terminology from linguistics and philosophy, an API contract involves both extension and intension: the boundaries of the current state of the world (extension) as well as the intended boundaries for other possible states of the world (intension: possible future implementations). In object-oriented programming, a common source of "possible future implementations" is subclassing from an existing class in an API.
A method defines a contract for any subclass method that would override it; it constrains possible implementations that a subclass could provide. In Java, the bare minimum contract for a method's inputs and outputs is the following:
* A method's parameter list is fixed; an overriding method in a subclass must declare precisely the same number and types of arguments.
* A method's return type is fixed; an overriding method in a subclass must declare precisely the same return type.
* The set of checked exceptions a method can throw (the method's declared exception classes and all their subclasses) establishes an upper bound. An overriding method in a subclass cannot throw any checked exceptions outside of that; it can, however, throw fewer exception types, or even none at all.
Note that the contract on exceptions concerns only checked exceptions; errors and runtime exceptions (that is, Error, RuntimeException, and their subclasses) are always permitted.
If a method, such as Object's toString method, is declared as throwing no checked exceptions, any overriding method you define must live within those bounds. You cannot define your own subclass of Exception and have your toString method throw that. In such a case, if you really need some exception to be thrown, you can resort to a subclass of RuntimeException, which is not checked or constrained by the compiler."
This description basically covers all the rules that a subclass must follow when overriding a method from superclass.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment