Java Reference
In-Depth Information
Note that the constant JANUARY is used in the class DemoMonthNumbers but is not
defined there. The class DemoMonthNumbers automatically gets the month constants
because it implements the MonthNumbers interface.
An interface cannot have instance variables, although it can use the syntax for
instance variables as a way to define constants. Any variables defined in an interface
must be public, static, and final, so Java allows you to omit those modifiers. The fol-
lowing is an equivalent definition of the interface MonthNumbers :
no instance
variables
public interface MonthNumbers
{
int JANUARY = 1,
FEBRUARY = 2, MARCH = 3, APRIL = 4, MAY = 5,
JUNE = 6, JULY = 7, AUGUST = 8, SEPTEMBER = 9,
OCTOBER = 10, NOVERMBER = 11, DECEMBER = 12;
}
Thus, an interface can be used to give a name for a group of defined constants, so
that you can easily add the needed constants to any class by implementing the inter-
face. This is really a different use for interfaces than what we have seen before, which
was to use interfaces to specify method headings. It is legal to mix these two uses by
including both defined constants and method headings in a single interface.
PITFALL: Inconsistent Interfaces
Java allows a class to have only one base class but also allows it to implement any number of
interfaces. The reason that a class can have only one base class is that if Java allowed two
base classes, the two base classes could provide different and inconsistent definitions of a
single method heading. Since interfaces have no method bodies at all, this problem cannot
arise when a class implements two interfaces. The ideal that the designers of Java apparently
hoped to realize was that any two interfaces will always be consistent. However, this ideal
was not fully realized. Although it is a rare phenomenon, two interfaces can be inconsis-
tent. In fact, there is more than one kind of inconsistency that can be exhibited. If you
write a class definition that implements two inconsistent interfaces, that is an error and the
class definition is illegal. Let's see how two interfaces can be inconsistent.
The most obvious way that two interfaces can be inconsistent is by defining two
constants with the same name but with different values. For example:
inconsistent
constants
public interface Interface1
{
int ANSWER = 42;
}
public interface Interface2
{
int ANSWER = 0;
}
Search WWH ::




Custom Search