Chapter 5. varargs

One of the coolest features of Java, and of any object-oriented language, is method overloading. While many might think Java’s strengths are its typing, or all the fringe APIs it comes with, there’s just something nice about having the same method name with a variety of acceptable arguments:

  Guitar guitar = new Guitar("Bourgeois", "Country Boy Deluxe",
		      GuitarWood.MAHOGANY, GuitarWood.ADIRONDACK,
  		      1.718);
  
  Guitar guitar = new Guitar("Martin", "HD-28");

  Guitar guitar = new Guitar("Collings", "CW-28"
  		      GuitarWood.BRAZILIAN_ROSEWOOD, GuitarWood.ADIRONDACK,
  		      1.718,
  		      GuitarInlay.NO_INLAY, GuitarInlay.NO_INLAY);

This code calls three versions of the constructor of a (fictional) Guitar class, meaning that information can be supplied when it’s available, rather than forcing a user to know everything about their guitar at one time (many professionals couldn’t tell you their guitar’s width at the nut). Here are the constructors used:

  public Guitar(String builder, String model) {
  }

  public Guitar(String builder, String model,
  		GuitarWood backSidesWood, GuitarWood topWood,
  		float nutWidth) {
  }

  public Guitar(String builder, String model,
  		GuitarWood backSidesWood, GuitarWood topWood,
  		float nutWidth,
  		GuitarInlay fretboardInlay, GuitarInlay topInlay) {
  }

Note

Enums, which ...

Get Java 5.0 Tiger: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.