Interface for constants

It's possible to place widely used constants in an interface. If a class implements such an interface, then the class can refer to those constants without a qualifying class name. This is only a minor advantage.

The static import feature should always be considered as a replacement for this practice.

Placing constants in an interface was a popular technique in the early days of Java, but now many consider it a distasteful use of interfaces, since interfaces should deal with the services provided by an object, not its data. As well, the constants used by a class are typically an implementation detail, but placing them in an interface promotes them to the public API of the class.

Example


interface OlympicMedal {
  static final String GOLD = "Gold";
  static final String SILVER = "Silver";
  static final String BRONZE = "Bronze";
}
 

Here's an example of using this interface to reference its constants:

public final class OlympicAthlete implements OlympicMedal {

  public OlympicAthlete(int aId){
    //..elided
  }

  //..elided

  public void winEvent(){
    //the athlete gets a gold medal
    //note the reference is NOT qualified, as
    //in OlympicMedal.GOLD
    fMedal = GOLD;
  }

  // PRIVATE
  private String fMedal; //possibly null
} 



See Also :
Type-Safe Enumerations
Class for constants
Use static imports rarely
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -