Java Reference
In-Depth Information
Interface1
Interface2
Constants
and
Methods
Interface3
Constants
Methods
Constants in an interface
are always
public, static and final
by default
Methods in an interface
are always
public and abstract
by default
The methods in an interface are always public and abstract , so you do not need to specify them as
such - it is considered to be bad programming practice to specify any attributes for them and you
definitely cannot add any attributes other than the defaults, public and abstract . This implies that
methods declared in an interface can never be static so an interface always declares instance
methods. The constants in an interface are always public , static and final , so you do not need to
specify the attributes for these either.
An interface is defined just like a class, but using the keyword interface rather than the keyword
class . You store an interface definition in a .java file with the same name as the interface. The name
that you give to an interface must be different from that of any other interface or class in the same
package. Just as for classes, the members of the interface - the constants and/or method declarations -
appear between braces. Let's start by looking at an interface that just defines constants.
Interfaces Containing Constants
Interfaces provide a very useful and easy to use mechanism for defining a set of constants and sharing
them across several classes. Here is an interface containing only constants:
public interface ConversionFactors {
double INCH _ TO _ MM = 25.4;
double OUNCE _ TO _ GRAM = 28.349523125;
double POUND _ TO _ GRAM = 453.5924;
double HP _ TO _ WATT = 745.7;
double WATT _ TO _ HP = 1.0/HP _ TO _ WATT;
}
You can save this in a file, ConversionFactors.java . Here we have five constants for conversions
of various kinds - remember that constants defined in an interface are automatically public , static ,
and final . We have no choice about this - constants defined in an interface always have these
attributes. Since they are static and final, you must always supply initializing values for constants
defined in an interface. The names given to these use capital letters to indicate that they are final and
cannot be altered - this is a common convention in Java. You can define the value of one constant in
terms of a preceding constant, as in the definition of WATT _ TO _ HP . If you try to use a constant that is
defined later in the interface - if, for example the definition for WATT _ TO _ HP appeared first - your code
will not compile.
Search WWH ::




Custom Search