|
|
|
|||
|
Overriding MethodsThe ability of a subclass to override a method in its superclass allows a class to inherit from a superclass whose behavior is "close enough" and then override methods as needed.
For example, all classes are descendents of the
Let's resurrect the
The return type, method name, and number and type of the parameters for
the overriding method must match those in the overridden method. The
overriding method can have a different throws clause as long as it
doesn't declare any types not declared by the throws clause in the
overridden method. Also, the access specifier for the overriding method
can allow more access than the overridden method, but not less. For
example, a protected method in the superclass can be made
public but not private.
Calling the Overridden MethodSometimes, you don't want to completely override a method. Rather, you want to add more functionality to it. To do this, simply call the overridden method using the Methods a Subclass Cannot OverrideA subclass cannot override methods that are declared final in the superclass (by definition, final methods cannot be overridden). If you attempt to override a final method, the compiler displays an error message similar to the following and refuses to compile the program:Also, a subclass cannot override methods that are declared Methods a Subclass Must OverrideA subclass must override methods that are declared abstract in the superclass, or the subclass itself must be abstract. The upcoming Writing Abstract Classes and Methods section discusses abstract classes and methods in detail. | |||
|