- 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
If I change the return type, will the method gets overloaded in java?
When a class has two or more methods by the same name but different parameters, at the time of calling, based on the parameters passed, respective method is called (or respective method body will be bonded with the calling line dynamically). This mechanism is known as method overloading.
Example
class Test{ 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[]){ Test t = new Test(); System.out.println(t.addition(25, 36)); System.out.println(t.addition(25, 50, 25)); } }
Output
61 100
Overloading based on different return type
In overloading it is must that the both methods have −
- same name.
- different parameters (different type or, different number or both).
Same return type is not mandatory. Therefore, you can overload methods with different return types if they have same name and different return types.
Example
In the following example we are trying to overload two methods: They have same name (addition) different parameters and different return types.
class Test{ public int addition(int a, int b){ int result = a+b; return result; } public float addition (float a, float b){ float result = a+b; return result; } public static void main(String args[]){ Test t = new Test(); System.out.println(t.addition(25, 36)); System.out.println(t.addition(100.25f, 36.1f)); } }
Output
61 136.35
Advertisements