No. |
Method Overloading | Method Overriding |
1) | Method overloading is used to increase the readability of the program. | Method overriding is used to provide the specific implementation of the method that is already provided by its super class. |
2) | Method overloading is performed within class. | Method overriding occurs in two classes that have IS-A (inheritance) relationship. |
3) | In case of method overloading, parameter must be different. | In case of method overriding, parameter must be same. |
4) | Method overloading is the example of compile time polymorphism. | Method overriding is the example of run time polymorphism. |
5) | In java, method overloading can’t be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter. | Return type must be same or covariant in method overriding. |
Example of Overloading:
// Java program to demonstrate working of method
// overloading in methods
class A {
public int foo(int a) { return 20; }
public char foo(int a, int b) { return ‘a’; }
}
public class Main {
public static void main(String args[])
{
A a = new A();
System.out.println(a.foo(1));
System.out.println(a.foo(1, 2));
}
}
Output:
20
a
Example of Overriding:
// Class Math
class Math {
// method say which is overridden method here
public void say() {
System.out.println(“This is class Math”);
}
}
// Class Topic
class Topic extends Math {
// method say which is overriding method here
public void say() {
System.out.println(“This is class Topics”);
}
}
class Main {
public static void main(String args[]) {
Math a = new Math(); // Math reference and object
Math b = new Topic(); // Math reference but Topic object
a.say(); // runs the method in Math class
b.say(); // runs the method in Topic class
}
}
Output:
This is class Math
This is class Topics