Java Reference
In-Depth Information
Compile this class and then move the file Item.class to the org\cadenhead\ecommerce
package on your system.
The Item class is a support class that represents a product sold by an online store. There
are private instance variables for the product ID code, name, how many are in stock
( quantity ), and the retail and sale prices.
Because all the instance variables of this class are private, no other class can set or
retrieve their values. Simple accessor methods are created in lines 36-54 of Listing 6.2 to
provide a way for other programs to retrieve these values. Each method begins with get
followed by the capitalized name of the variable, which is standard in the Java class
library. For example, getPrice() returns a double containing the value of price . No
methods are provided for setting any of these instance variables—that is handled in the
constructor method for this class.
Line 1 establishes that the Item class is part of the org.cadenhead.ecommerce package.
Cadenhead.org is the personal domain of this topic's coauthor, so
this project follows Sun's package-naming convention by beginning
with a top-level domain (org), following it with the second-level
domain name (cadenhead), and then by a name that describes the
purpose of the package (ecommerce).
NOTE
The Item class implements the Comparable interface (line 5), which makes it easy to sort
a class's objects. This interface has only one method, compareTo( Object ) , which returns
an integer.
The compareTo() method compares two objects of a class: the current object and another
object passed as an argument to the method. The value returned by the method defines
the natural sorting order for objects of this class:
If the current object should be sorted above the other object, return -1 .
n
6
If the current object should be sorted below the other object, return 1 .
n
If the two objects are equal, return 0 .
n
You determine in the compareTo() method which of an object's instance variables to
consider when sorting. Lines 27-34 override the compareTo() method for the Item class,
sorting on the basis of the price variable. Items are sorted by price from highest to
lowest.
After you have implemented the Comparable interface for an object, two class methods
can be called to sort an array, linked list, or other collection of those objects. You see this
when Storefront.class is created.
Search WWH ::




Custom Search