- 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
Can we overload a method based on different return type but same argument type and number, 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 division(int a, int b){ int result = a/b; return result; } public double division (float a, float b){ double result = a/b; return result; } }
Overloading with same arguments and different return type −
No, you cannot overload a method based on different return type but same argument type and number in java.
In overloading it is must that the both methods have −
- same name.
- different parameters (different type or, different number or both).
The return type doesn’t matter. If they don’t have different parameters, they both are still considered as same method and a compile time error will be generated.
Example
In the following example we are trying to overload two methods: They have same name (division) same parameters (two integers).
class Test{ public int division(int a, int b){ int result = a/b; return result; } public double division (int a, int b){ double result = a/b; return result; } }
Compile time error
If you try to compile the above program, since the parameters are not different Java compiler considers them as same methods and generates the following error.
OverloadingExample.java:6: error: method division(int,int) is already defined in class Test public static double division (int a, int b){ ^ 1 error
- Related Articles
- Can we change return type of main() method in java?
- Can we overload Java main method?
- Can we overload the main method in Java?
- Can we overload or override a static method in Java?\n
- Return an array of zeroes with the same shape as a given array but with a different type in Numpy
- Different ways to overload a method in Java
- Covariant return type in Java\n
- Importance of return type in Java?
- Can we return this keyword from a method in java?
- Return a new array with the same shape as a given array but change the default type in Numpy
- method overloading and type promotion in Java
- Can we overload methods of an interface in Java?
- Can we Overload or Override static methods in Java?
- Does a constructor have a return type in Java?
- Return True if first argument is a typecode lower/equal in type hierarchy in Python
