Java Reference
In-Depth Information
LISTING 8.12
//********************************************************************
// Family.java Author: Lewis/Loftus
//
// Demonstrates the use of variable length parameter lists.
//********************************************************************
public class
Family
{
private
String[] members;
//-----------------------------------------------------------------
// Constructor: Sets up this family by storing the (possibly
// multiple) names that are passed in as parameters.
//-----------------------------------------------------------------
public
Family (String ... names)
{
members = names;
}
//-----------------------------------------------------------------
// Returns a string representation of this family.
//-----------------------------------------------------------------
public
String toString()
{
String result = "";
for
(String name : members)
result += name + "\n";
return
result;
}
}
The
Family
class is shown in Listing 8.12. The constructor simply stores a refer-
ence to the array parameter until it is needed. By using a variable-length parameter
list for the constructor, we make it easy to create a family of any size.
SELF-REVIEW QUESTIONS
(see answers in Appendix N)
SR 8.20
How can Java methods have variable-length parameter lists?
SR 8.21
Write a method called
distance
that accepts a multiple number of
integer parameters (each of which represents the distance of one leg of
a journey) and returns the total distance of the trip.
Search WWH ::
Custom Search