• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Method Overloading with default param values

 
Anjanesh Lekshminarayanan
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Why doesnt this method overloading work ?


I was trying to assign default values
(like public static String foo(byte a = 5, byte b = 10))
only to realize tha Java doesnt support default assignments.

I get


JDK 6

Thanks
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15441
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you sure that that's exactly the error you are getting? Because that would be strange. I compiled this small test program:

And got the following errors:

Note that the compiler does not complain that it can't find foo(byte, byte) - it does complain that it can't find variants of this function that take an int parameter. That is because the literal numeric values are of type int, not byte. They are not automatically converted to byte.

You can either (1) cast the literals to byte, or (2) use int instead of byte in the method arguments.
 
Anjanesh Lekshminarayanan
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah..Thanks.

Yes - you're right, I got

I wanted to use byte to save memory since I know the values are going to be from 1-50 or so.

So I got to typecast all literals manually ?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15441
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Anjanesh Lekshminarayanan:
So I got to typecast all literals manually ?

If you explicitly want these to be interpreted as byte and not as int, yes.

There's one special case for byte in the Java language. When you declare a byte and you assign a literal value to it, you don't have to cast it.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Anjanesh Lekshminarayanan:

I wanted to use byte to save memory


Using byte-sized method parameters will not have any effect on memory usage. Using bytes as member variable may.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic