Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

In this noncompliant code example, overloading variable arity methods makes it unclear which definition of the displayBooleans() method is invoked.:

Code Block
bgColor#FFCCCC
class Varargs {
  private static void displayBooleans(boolean... bool) {
    System.out.print("Number of arguments: " + bool.length + ", Contents: ");

    for (boolean b : bool)
      System.out.print("[" + b + "]");
  } 
  private static void displayBooleans(boolean bool1, boolean bool2) {
    System.out.println("Overloaded method invoked");  
  }
  public static void main(String[] args) {
    displayBooleans(true, false);
  }
}

When run, this program output:outputs

Code Block
Overloaded method invoked

...

To avoid overloading variable arity methods, use distinct method names to ensure that the intended method is invoked, as shown in this compliant solution.:

Code Block
bgColor#ccccff
class Varargs {
  private static void displayManyBooleans(boolean... bool) {
    System.out.print("Number of arguments: " + bool.length + ", Contents: ");

    for (boolean b : bool)
      System.out.print("[" + b + "]");
  } 
  private static void displayTwoBooleans(boolean bool1, boolean bool2) {
    System.out.println("Overloaded method invoked");  
    System.out.println("Contents: [" + bool1 + "], [" + bool2 + "]");  
  }
  public static void main(String[] args) {
    displayManyBooleans(true, false);
  }
}

...