Explain how method overloading and overriding work.
Static versus Dynamic Polymorphism
Let us enlarge on the concept of polymorphism.
Polymorphism can be of two forms:
static and
dynamic.
When different forms of a single entity are resolved at compile time (early binding), such polymorphism is called static polymorphism.
When different forms of a single entity are resolved during runtime (late binding), such polymorphism is called dynamic polymorphism. Overloading is an example of static polymorphism.
Overloading and overriding Methods
Multiple methods of the same name but different signatures.
A method is overloaded in a class declaration when two or more methods have the same name but different parameters.
That is, the methods differ in the number of parameters, types of parameters, or ordering of their parameter types.
Examples of overloading are the println() methods of the java.io.PrintStream class.
Two methods may not be declared with the same name and parameter types but with different return types.
This restriction also applies to methods that are inherited from superclasses.
However, two methods with the same name and different parameter types may have different return types.
Overriding occurs when a method is declared with the same name, parameter types, and return type as a method that is inherited from one of its superclasses. Overriding allows a class to replace a superclass method with one of its own. The following restrictions apply to overriding:
Methods that are declared as final may not be overridden.
The overriding method must be as accessible as the overridden method. If the overridden method is public, then the overriding method must be public. If the overridden method is protected, then the overriding method must be public or protected. If the overridden method is declared with package access, then the overriding method must not be private.
The overriding method may not throw any exceptions that are not covered by the throws clause of the overridden method.
Static methods may not be overridden to be non-static.
Since private methods are not inherited, they may not be overridden.