Here you will learn about difference between method overloading and method overriding in java with program examples.
When a class have methods with same name but different arguments list then it is called method overloading. On the other hand if two classes (parent and child) have methods with same name and same arguments list then it is called method overriding.
There are various other differences between them that are discussed below in tabular form.
Difference between Method Overloading and Method Overriding in Java
Method Overloading | Method Overriding |
When a class having several methods with the same name but with different arguments then it is known as method overloading. | When parent and child class have methods with same name and arguments then it is called as method overriding. |
Method overloading occur within one class only. | Method overriding occur within two classes (parent and child). |
It is an example of compile time polymorphism. | It is an example of run time polymorphism. |
Methods must have different signature (same name but different number of arguments and their type). | Methods must have same signature (same name and arguments list). |
Used to add more to method’s behavior. | Used to change the method’s existing behavior. |
Method Overloading Example
public class MethodOveloadingExample { int sum(int a) { return a+a; } int sum(int a, int b) { return a+b; } float sum(float a, float b) { return a+b; } public static void main(String args[]) { MethodOveloadingExample obj = new MethodOveloadingExample(); System.out.println(obj.sum(5)); System.out.println(obj.sum(5, 10)); System.out.println(obj.sum(5.5f, 10.5f)); } }
Output
10
15
16.0
You can observe in above program and output that method is called depending upon number of arguments and their type.
Method Overriding Example
class Bike { public int speed() { return 100; } } class Hero extends Bike { @Override public int speed() { return 150; } public static void main(String args[]) { Bike obj = new Hero(); int num = obj.speed(); System.out.println("Speed is "+num); } }
Output
Speed is 150
Comment below if you have queries or found any information incorrect in above tutorial for difference between method overloading and overriding in Java.