In this tutorial, we will write a program for method overriding and method overloading. Before that, you should have knowledge on the following topic in Java.
Example of method overriding in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class Dog { public void display() { System.out.println("I am A Dog"); } } class breed extends Dog { public void display() { System.out.println("Breed: German Shepard"); } } public class Main { public static void main(String args[]) { Dog d = new Dog(); // Animal reference and object Dog b = new breed(); // Animal reference but Dog object d.display(); // runs the method in Animal class b.display(); // runs the method in Dog class } } |
Output method overriding:
I am A Dog
Breed: German Shepard
Explanation:
In the above example, we can see that ‘b‘ is a type of dog but still executes the display method in the breed class. In the runtime, JVM first looks at the object type and runs the method that belongs to that particular object.
Since the class Dog has the method display, the compiler will have no problem in compiling, and during runtime, the method specific for that particular object will run.
1. Method overloading by changing the data type of Arguments
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class MethOverloadingTest { void add (int x, int y) { System.out.println("sum is "+(x+y)) ; } void add (double x, double y) { System.out.println("sum is "+(x+y)); } } public class Main { public static void main (String[] args) { MethOverloadingTest sum = new MethOverloadingTest(); sum.add (5,5); // method with int parameter is called. sum.add (5.5, 5.5); //method with float parameter is called. } } |
Output:
sum is 10
sum is 11.0
2. Method overloading by changing the number of the argument
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class MethOverloadingTest2 { void Info() { System.out.println("Argument List is empty") ; } void Info (String c, int id) { System.out.println("\nName:"+c+" Id:"+id); } void Info (String c, int id, int age) { System.out.println("\nName:"+c+" Id:"+id+" Age:"+age); } } public class Main { public static void main (String[] args) { MethOverloadingTest2 sum = new MethOverloadingTest2(); sum.Info(); //method with empty parameter is called. sum.Info ("Karan",1101); // method with two parameter is called. sum.Info ("Prashant",1102,23); //method with three parameter is called. } } |
Output of Method overloading:
Argument List is empty
Name:Karan Id:1101
Name:Prashant Id:1102 Age:23