Page 452 - Introduction to Programming with Java: A Problem Solving Approach
P. 452
418 Chapter 10 Arrays and ArrayLists
/*************************************************************
*
Bear.java
Dean & Dean
This class models a toy bear.
**************************************************************/
*
*
*
public class Bear
{
}
// end Bear class
private final String MAKER; // bear's manufacturer
private final String TYPE; // type of bear
//***********************************************************
public Bear(String maker, String type)
{
}
MAKER = maker;
TYPE = type;
//***********************************************************
public void display()
{
Apago PDF Enhancer
System.out.println(MAKER + " " + TYPE);
}
Figure 10.28 Class that represents a toy bear
able. Since there’s no assignment to a Bear reference variable, that’s an example of an anonymous ob- ject. As an alternative, the statement could have been written with a Bear reference variable like this:
Bear stdBear = new Bear("Acme", "brown teddy");
bears.add(stdBear);
But why bother with using two statements instead of one? The new bear’s reference gets stored in the bears ArrayList and that’s where it’s processed. There’s no need to store it in a second place (e.g., in the stdBear reference variable), so in the interest of code compactness, don’t.
Now let’s examine the bottom part of the BearStore class, shown in Figure 10.29b. The BearStore class’s getUserSpecifiedBear method prompts the user for a customized bear’s maker and type and returns the newly created bear. Here’s the return statement:
return new Bear(maker, type);
Note that there’s no reference variable for the new bear. Thus, the new bear is considered to be an anon- ymous object. The return statement returns the new bear to the addUserSpecifiedBears method, where it gets added to the bears ArrayList.