Jump to Real's How-to Main page

Use globally defined constants

Via a class
This technique is useful for constants defined on a corporate level. They are very generic by nature. The CONSTANT class is included in the classpath.
public class CONSTANT {
  public static final integer SUCCESS = 1;
  public static final integer FAILURE = -1;
  public static final integer NOTFOUND = 0;
}
Since the members of the class are defined as "static", there is no need to instantiate the class. To use a constant, simply use CONSTANT.[constant name]
if (myMethod()==CONSTANT.SUCCESS) {
   ...;
   }
else {
   ...;
}
Via an interface
This technique can be used if the constants are not really global but especially designed to be used in a specific application for example. An application-level class needs to implement the interface to be able to see the constant definitions.
public interface APPCONSTANT {
  public static final String APPNAME = "The Super APP";
  public static final String APPVERSION = "version 1.0";
  public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver";
}
then to use a constant, simply implement the interface
public class TheAppFrame extends Frame
  implements APPCONSTANT {
 
  TheAppFrame {
    ...
    setTitle(APPNAME);
    ...
    }
...
}
NOTE : This is not considered as good practice (depending on who you are talking to!) to use an interface this way.

NOTE: By convention, constant name are always in CAPITALS.

JDK1.5
JDK1.5 import statement can be used to import only static member from a class.

import static java.lang.Math.*;

public class DemoImport {
   public static void main(String[] args) {
      double x = 16.0;
      System.out.println(abs(x));
      System.out.println(PI);
      // instead of  System.out.println(Math.abs(x));
      //             System.out.println(Math.PI);
   }
}

If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2005
[ home ]