First, the code - I've included only the relevant changes, so they're easy to see.
public class Product implements Comparable<Product>
// rest of stuff goes here
public int compareTo(Product other)
int comparison = 0;
comparison = other.getNumInStock() - this.getNumInStock();
The first thing to notice is that we're now saying the Product implements the Comparable interface, specialized for Product. In other words: we're telling the compiler we can compare Products to other Products.
Next, notice that compareTo() now takes a *Product* as the "other" object. If you had just implemented the Comparable interface (without specializing it for Product), you would get an Object and not a Product, which you'd then have to typecast and be all messy about.
Finally, notice the @Override attribute. This tells the compiler that you're *expecting* a base class to provide a compareTo method that you want to override - if it doesn't (you forgot to add an "implements interface
", or have misspelled the method name, or aren't using the right argument overloads), you'll get a compiler warning rather than scratching your beard wondering why your (not really
) overriden method is never called.
Hope this helps!