Method overloading is a concept of polymorphism, where poly means many operations will be done by single function, for example calculator. Polymorphism will have two types as follows.
The Advantages of Java is as follows:
- Method Overloading
- Method Overriding
Same method with different number of parameters in the same class then it is called as
Method Overloading. Following is an example.
[java]
public class methodoverloading {
public static void main(String[] args) {
int a = 14;
int b = 7;
double c = 9.3;
double d = 8.4;
int result1 = minFunction(a, b);
// same function name with different parameters
double result2 = minFunction(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}
// for integer
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
[/java]
Output
When compile the code following is the output will be generated.
[java]
Minimum Value = 7
Minimum Value = 8.4
[/java]
If subclass has the same method as declared in the base class, it is known as
Method Overriding in java. The following is an example.
[java]class Splessons{
void run(){System.out.println("Welcome to splessons");}
}
class Tutorials extends Splessons{
void run(){System.out.println("It will provide all tutorials");}
public static void main(String args[]){
Tutorials obj = new Tutorials ();
obj.run();
} [/java]
In the above example,
run() method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes and as per the definition
method overriding placed.
Output:
[java]It will provide all tutorials[/java]
Note:
Overloading happens at
compile-time while Overriding happens at
runtime.The binding of overloaded method call to its definition has happens at compile-time however binding of overridden method call to its definition happens at runtime.
Static methods can be overloaded which means a class can have more than one static method of same name. Static methods cannot be overridden, even if you declare a same static method in child class it has nothing to do with the same method of parent class.