Java Reference
In-Depth Information
To compile Storefront.java , the Item class must be stored in a folder that corresponds
to the org.cadenhead.ecommerce package name. After you have compiled Storefront.
class , move the file to the same folder as Item.class .
The Storefront.class is used to manage a collection of products in an online store.
Each product is an Item object, and they are stored together in a LinkedList instance
variable named catalog (line 6).
The addItem() method in lines 8-13 creates a new Item object based on four arguments
sent to the method: the ID, name, price, and quantity in stock of the item. After the item
is created, it is added to the catalog linked list by calling its add() method with the
Item object as an argument.
The getItem() and getSize() methods provide an interface to the information stored in
the private catalog variable. The getSize() method in lines 19-21 calls the
catalog.size() method, which returns the number of objects contained in catalog .
Because objects in a linked list are numbered like arrays and other data structures, you
can retrieve them using an index number. The getItem() method in lines 15-17 calls
catalog.get() with an index number as an argument, returning the object stored at that
location in the linked list.
The sort() method in lines 23-25 is where you benefit from the implementation of the
Comparable interface in the Item class. The class method Collections.sort() sorts a
linked list and other data structures based on the natural sort order of the objects they
contain, calling the object's compareTo() method to determine this order.
After you compile Storefront class, you're ready to develop a program that actually
uses the org.cadenhead.ecommerce package. Open the folder on your system where
you've been creating the programs of this topic (such as \J21work ) and create
GiftShop.java from Listing 6.4.
CAUTION
Don't save GiftShop.java in the same folder on your system where
the classes of the org.cadenhead.ecommerce package are stored.
It's not part of the package (as you'll note by the absence of a
package org.cadenhead.ecommerce statement). The Java compiler
exits with an error message because it wasn't expecting to find
Storefront.class in the same folder as the GiftShop application.
6
Search WWH ::




Custom Search