• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why return type is not sufficient for method overloading in java ?  RSS feed

 
Prabhat Ranjan
Ranch Hand
Posts: 397
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Example:

if we write :

int test();

String test();

call :

String str = "prabhat" + test();


Result is Duplicate method at compile time only !
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess the short answer is... that is how it is defined in the Java language specification. Section 8.4.9, to be exact.

Unless, of course, the OP is asking why it was specified that way, which I don't know.

Henry
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Dog extends Animal {};
class Cat extends Animal {};

Dog test();

Cat test();

Animal A = test();

Which version of test should the JVM run?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
fred rosenberger wrote:
Which version of test should the JVM run?


I agree with Fred, in that it is certainly easy to confuse the compiler, if return types were involved. But it is also possible to confuse the compiler, even if return types are not involved. This is why the JLS added the qualifier that the parameters be not "override-equivalent".

But... if I had to take a guess why, I will say that it is because no other languages define overloading this way (return type as part of the signature) -- certainly not the C++ language which Java was modelled after.

Henry
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!