• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

default arguments

 
fred cook
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, is there such a thing in Java called default arguments or default parameters. If so, how do you do it? Tell me if this would be correct usage of a default argument (if there is one):
public void myMethod (int myDefault = 0)
{
...
}
 
Matthew Phillips
Ranch Hand
Posts: 2676
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I haven't seen a method definition like that, but let me see if I understand what you want to do. If you want your method to accept a parameter, but be able to run without it then you need to overload the method. Overloading the method allows you to define several methods with the same name, but different parameters. For example:



By overloading the method you allow an outside source to call it with a parameter or without. If it is called without a parameter, a default value will be set and then the method with the parameter will be called with that default method.
Matthew Phillips

[This message has been edited by Matthew Phillips (edited June 13, 2001).]
 
fred cook
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The main reason I ask this is because I know you can do it in C, but I don't want to overload my function (too much repeated code). If anyone else knows for sure whether or not Java has default arguments let me know.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, you need to overload the method to achieve that. It is ONLY 4 lines of code there is nothing of substance repeated. Whats the big deal?

[This message has been edited by Cindy Glass (edited June 13, 2001).]
 
fred cook
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK, yes that works...but I just need to know whether there is such a thing as default arguments, or do I HAVE to do that.
[This message has been edited by fred cook (edited June 15, 2001).]
 
Mike Curwen
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Method headers and method calls must agree in number, type and order of parameters and arguments.

So I think the answer is no, and yes.

No, there are no default parameter values in Java, and Yes, you have to do that (overload).
 
Conrad Kirby
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks you guys! (this is the same person as 'Fred Cook')
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic