Witscale Test Center

3.7 Interface and modifiers > 3.7.2 Interface constants and modifiers


3.7.2 Interface constants and modifiers

Like methods, the variables declared in an interface are also implicitly public. In addition to that, the interface variables are also implicitly final and static. You cannot give any other modifier to the interface variable than public, static and final. Note that even when you don’t give any modifier, these three are assumed.

There are strong reasons why only these three modifiers are allowed. As we know, interfaces do not have any implementation, so they are never instantiated. Therefore, they cannot possibly have any instance variables. Their variables must be static. The interface variables are also declared as final to ensure that they are initialized by giving them value right where they are declared. Hence all implementing classes have the value specified in interface declaration for the declared variable. Like all final variables, you cannot change the assigned value of interface variable. This is why interface variable are also called as interface constants.

Interface constants are useful to declare the constant values that make sense in the context of the common behavior they are describing. For example, in the Searchable interface, all searchable classes may state the common wild card characters in the search strings as interface constants:

 

public abstract interface Searchable {

  char MATCH_ZERO_OR_MORE = ‘*’;

  char MATCH_ONLY_ONE = ‘?’;

  void Search(String searchString);

  void Search(String searchString, boolean ignoreCase);

}

 

Note that the interface variables in above code such as the MATCH_ZERO_OR_MORE do not explicitly have any access modifier. However their access is not default. All interfaces variables have public access. Hence both variables define in above code are public, static and final. Usually you will see the interface variable names are in all capital case. This convention is used to indicate that they are constants.

 

Watch out for a code that tries to reassign value to interface constants in the implementing class. For instance, in above example if you assign ‘+’ to MATCH_ONLY_ONE in the class implementing the interface Searchable, that class will not compile because interface constants are final and cannot be reassigned.