
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Overload Methods of an Interface in Java
Polymorphism is the ability of an object to perform different actions (or, exhibit different behaviors) based on the context.
Overloading is one of the mechanisms to achieve polymorphism where a class contains two methods with the same name and different parameters.
Whenever you call this method the method body will be bound with the method call based on the parameters.
Example
In the following Java program, the Calculator class has two methods with name addition the only difference is that one contains 3 parameters and the other contains 2 parameters.
Here, we can call the addition method by passing two integers or three integers. Based on the number of integer values we pass respective method will be executed.
public class Calculator { public int addition(int a , int b){ int result = a+b; return result; } public int addition(int a , int b, int c){ int result = a+b+c; return result; } public static void main(String args[]){ Calculator cal = new Calculator(); System.out.println(cal.addition(12, 13, 15)); } }
Output
40
Overloading methods of an interface
Yes, you can have overloaded methods (methods with the same name different parameters) in an interface. You can implement this interface and achieve method overloading through its methods.
Example
import java.util.Scanner; interface MyInterface{ public void display(); public void display(String name, int age); } public class OverloadingInterfaces implements MyInterface{ String name; int age; public void display() { System.out.println("This is the implementation of the display method"); } public void display(String name, int age) { System.out.println("Name: "+name); System.out.println("Age: "+age); } public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter your name: "); String name = sc.next(); System.out.println("Enter your age: "); int age = sc.nextInt(); OverloadingInterfaces obj = new OverloadingInterfaces(); obj.display(); obj.display(name, age); } }
Output
Enter your name: Krishna Enter your age: 25 This is the implementation of the display method Name: Krishna Age: 25