3.8 Implementing Interfaces with Enums
Now that you're starting to add
methods to your enums (see the previous
lab on Adding Methods to an Enum for details if you're skipping
around), you may find that you want to define methods in an interface,
and implement that interface with one, two, or even more enums. You
may also want to have an enum implement an interface, and have
classes implement that same interface. All this is possible, and even quite
simple.
3.8.1 How do I do that?
Example 3-8 is a very simple interface that could describe enumerated
types that represent features on all sorts of instruments (not just guitars).
Example 3-8. Base interface for feature enums
It's trivial to make GuitarFeatures implement this interface, as the methods
package com.oreilly.tiger.ch03;
public interface Features {
/** Get the upcharge for this feature */
public float getUpcharge( );
/** Get the description for this feature */
public String getDescription( );
}
are already written:
Now you can create BanjoFeatures, MandolinFeatures, and more, all
public enum GuitarFeatures implements Features {
using the same interface as a starting point. This creates a nice sense of
uniformity among your enums, and is highly recommended.