Is it possible to implement default arguments (ala C++) in Java?

John Mitchell

Not exactly. There a couple of basic approaches to more or less simulate this capability... The first is to use method overloading where simpler versions of the method (i.e., those with fewer parameters) invoke the more complete version of the method with the default values appropriately specified in the argument list. The second is to identify special cases directly and then substitute the default values.

Here's an example of the first from Scott Stanchfield:

Basically, you define one method that has all of the parameters present. This method will perform all of the necessary processing.

Then, you overload the method will some parameters missing. These overloaded methods call the one with all parameters by passing in default values.

For example:

public void foo(String name,
                int age,
                double income,
                Color eyeColor) {
  this.name = name;
  this.age = age;
  this.income = income;
  this.eyeColor = eyeColor;
}

public void foo(String name,
                int age,
                double income) {
  foo(name, age, income, Color.blue);
}

public void foo(String name,
                int age) {
  foo(name, age, 10000, Color.blue);
}

public void foo(String name) {
  foo(name, 20, 10000, Color.blue);
}

public void foo(String name, 
                double income) {
  foo(name, 20, income, Color.blue);
}

Here's an example of the second approach:

public void foo(String name,
                int age,
                double income,
                Color eyeColor) {
  if (name == null)
    this.name = "John Doe";
  if (age <= 0)
    this.age = 20;
  if (income <= 0)
    this.income = 10000;
  if (Color == null)
    this.color = Color.blue;
}

Finally, here's an example of mixing both of those approaches by Ivo Limmen:

public void test() {
   this.test(null, null);
}
public void test(String p1) {
   this.test(null, null);
}
public void test(String p1, String p2) {
   if(p1 == null) {
      ...
   } else {
      ...
   }
   if(p2 == null) {
      ...
   } else {
      ...
   }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact