Page 453 - Introduction to Programming with Java: A Problem Solving Approach
P. 453
10.13 ArrayList Example Using Anonymous Objects and the For-Each Loop 419
/*******************************************************************
*
BearStore.java
Dean & Dean
This class implements a store that sells toy bears.
*******************************************************************/
*
*
*
import java.util.Scanner;
import java.util.ArrayList;
public class BearStore
{
ArrayList<Bear> bears = new ArrayList<Bear>();
//****************************************************************
// Fill store with specified number of standard teddy bears.
public void addStdBears(int num)
{
for (int i=0; i<num; i++)
{
}
bears.add(new Bear("Acme", "brown teddy"));
Apago PDF Enhancer
} // end addStdBears
//****************************************************************
// Fill store with specified number of customized bears.
public void addUserSpecifiedBears(int num)
{
for (int i=0; i<num; i++)
{
}
bears.add(getUserSpecifiedBear());
anonymous object as argument
Returned anonymous object becomes argument in this method call.
} // end addUserSpecifiedBears
Figure 10.29a Class that implements a toy-bear store—part A When to Use an Anonymous Object
The bear-store program contains several specific examples of using anonymous objects. In general, you’ll see anonymous objects being used in two circumstances:
1. When passing a newly created object into a method or constructor. For example: bears.add(new Bear("Gund", "Teddy"));
2. When returning a newly created object from a method. For example: return new Bear(maker, type);