Difference between Method Overloading and Method Overriding
Method Overloading:
When two or more methods in the same class have the same name but different parameters, it is called method overloading. It is used when objects are required to perform similar tasks but using different input parameters.
Example:
class House { int length, width; House(int x, int y) // creating constructor 1 { length=x; width=y; } House(int x) // creating constructor 2 { length=width=x; } int area() { return(length*width); } public static void main(String arg[]) { House h1=new House(); System.out.println(h1.House(20,16)); House h2=new House(); System.out.println(h2.House(20)); } }
Output:
320
20
Method Overriding:
When a method in the subclass has the same name, same arguments, and same return type as a method in the superclass. Then the method is defined in the subclass and is invoked and executed instead of the one superclass. That is called Method Overriding.
Example:
class super { int x; super(int x) { this.x=x; } void display() { System.out.println("Super x :"+x); } } class add extends super { int y; add(int x, int y) { super(x); this.y=y; } void display() { System.out.println("Super x :"+x); System.out.println("add y :"+y); } } class test { public static void main(String args[]) { add a1=new add(50, 100); a1.display(); } }
Output:
super x : 50
add y : 100
Method Overloading vs Method Overriding:
1. It is a compile-time polymorphism | 1. It is a run-time polymorphism |
2. It occurs within the class | 2. It occurs into two classes with inheritance relationships |
3. In method overloading, methods must have the same name and but different parameters | 3. In method overriding, methods must have the same name and same parameters |
4. Method overloading is also called Static binding | 4. Method overriding is also called Dynamic binding |
5. It may or may not require inheritance | 5. It always requires inheritance |
6. Private and final methods can be overloaded | 6. Private and final methods can’t be overridden |
7. In method overloading, the argument list should be different | 7. In method overriding, the argument list should be the same |
8. It helps to increase the readability of the program. | 8. It helps to grant the specific implementation of the method which is already provided by its parent class or super class. |