Java Reference
In-Depth Information
You should realize that the results for the
m2()
method in class
OME2
are the same for both versions and hence
OME2.m2()
is not overloaded.
Table
16-2
lists some important differences between method overriding and method overloading.
Table 16-2.
Some Important Differences Between Method Overriding and Method Overloading
Method Overriding
Method Overloading
Overriding involves inheritance and at least two classes.
Overloading has nothing to do with inheritance.
Overloading involves only one class.
It occurs when a class defines a method with the same
name, the same number of parameters of the same type in
the same order as defined by its superclass.
It occurs when a class defines more than one method
with the same name. All methods with the same name
must differ at least in one respect from others - the
number of parameters, their types or orders.
The return type of the overriding method must be
assignment substitutable with the return type of the
overridden method.
Return types of overloaded methods do not play any
roles in overloading.
The overriding method cannot have additional throws
clause than the overridden method. It can have the same or
less restrictive list of exceptions as the overridden method.
Throws clauses of overloaded methods do not play
any roles in overloading.
Overriding applies only to instance (non-static) methods.
Any method (static or non-static) can be overloaded.
Method overloading is another kind of polymorphism where the same method name has different meanings.
Method overloading is bound at compile time as opposed to method overriding that is bound at runtime. Note that
the compiler only resolves the version of the overloaded methods that will be called. It determines which version of
the overloaded method will be called matching the actual parameters with the formal parameters of the overloaded
methods. If the overloaded method is an instance method, which code will be executed is still determined at runtime
using late binding.
For an overloaded method call, the compiler chooses the most specific method. If it does not find an exact match,
it will try to look for a more generic version by converting the actual parameter type to a more generic type using the
rules of automatic type widening. Listing 16-15 demonstrates how the compiler chooses an overloaded method.
Listing 16-15.
A Test Program That Demonstrates How the Compiler Chooses the Most Specific Method from Several
Versions of an Overloaded Method
// OverloadingTest.java
package com.jdojo.inheritance;
public class OverloadingTest {
public double add(int a, int b) {
System.out.println("Inside add(int a, int b)");
double s = a + b;
return s;
}
public double add(double a, double b) {
System.out.println("Inside add(double a, double b)");
double s = a + b;
return s;
}