THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

References of interface type, however, can be used only to access members of that interface. For example, the
following will produce a compile-time error:


Comparable obj = new Point();
double dist = obj.distance(p1); // INVALID: Comparable has
// no distance method


If you want to treat obj as a Point object you must explicitly cast it to that type.


You can invoke any of the Object methods using a reference of an interface type because no matter what
interfaces the object implements, it is always an Object and so has those methods. In fact, any interface that
does not extend some other interface implicitly has members matching each of the public methods of Object
(unless the interface explicitly overrides them). Hence, the following is legal:


String desc = obj.toString();


as is assigning an interface reference to an Object reference.


4.2. Interface Declarations


An interface is declared using the keyword interface, giving the interface a name and listing the interface
members between curly braces.


An interface can declare three kinds of members:



  • constants (fields)

  • methods

  • nested classes and interfaces


All interface members are implicitly public, but, by convention, the public modifier is omitted. Having
non-public members in an interface would make little sense; where it does make sense you can use the
accessibility of the interface itself to control access to the interface members.


We defer a discussion of nested classes and interfaces until Chapter 5.


4.2.1. Interface Constants


An interface can declare named constants. These constants are defined as fields but are implicitly public,
static, and finalagain, by convention, the modifiers are omitted from the field declarations. These fields
must also have initializersblank finals are not permitted. Annotations can also be applied to the fieldssee
Chapter 15.


Because interfaces contain no implementation details, they cannot define normal fieldssuch a definition would
be dictating implementation policy to the classes that choose to implement the interface. Interfaces can define
named constants because these are useful in the design of types. For example, an interface that had differing
levels of verbosity in its contract might have the following:

Free download pdf