aspose file tools*
The moose likes Java in General and the fly likes Method Overloading with default param values Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Method Overloading with default param values" Watch "Method Overloading with default param values" New topic
Author

Method Overloading with default param values

Anjanesh Lekshminarayanan
Ranch Hand

Joined: Oct 21, 2003
Posts: 46
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


Anjanesh Lekshminarayanan
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14266
    
  21

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Anjanesh Lekshminarayanan
Ranch Hand

Joined: Oct 21, 2003
Posts: 46
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

Joined: Aug 16, 2005
Posts: 14266
    
  21

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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Method Overloading with default param values