- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Using Method Overloading in Java
A class can have multiple methods with the same name but the parameter list of the methods should not be the same. This is known as method overloading. Method overloading is somewhat similar to constructor overloading.
A program that demonstrates this is given as follows −
Example
class PrintValues { public void print(int val) { System.out.println("The value is: " + val); } public void print(double val) { System.out.println("The value is: " + val); } public void print(char val) { System.out.println("The value is: " + val); } } public class Demo { public static void main(String[] args) { PrintValues obj = new PrintValues(); obj.print(7); obj.print(19.3); obj.print('A'); } }
Output
The value is: 7 The value is: 19.3 The value is: A
Now let us understand the above program.
The PrintValues class is created with three methods print() in the implementation of method overloading. One of these takes a parameter of type int, another takes a parameter of type double and the last takes a parameter of type char. A code snippet which demonstrates this is as follows:
class PrintValues { public void print(int val) { System.out.println("The value is: " + val); } public void print(double val) { System.out.println("The value is: " + val); } public void print(char val) { System.out.println("The value is: " + val); } }
In the main() method, object obj of class PrintValues is created and the print() method is called three times with parameters 7, 19.3 and ‘A’ respectively. A code snippet which demonstrates this is as follows:
public class Demo { public static void main(String[] args) { PrintValues obj = new PrintValues(); obj.print(7); obj.print(19.3); obj.print('A'); } }