Java Reference
In-Depth Information
class Test implements Color, TrafficLight {
public static void main(String[] args) {
System.out.println(GREEN); // compile-time error
System.out.println(RED); // compile-time error
}
}
it is not astonishing that the reference to
GREEN
should be considered ambiguous, be-
cause class
Test
inherits two different declarations for
GREEN
with different values.
The point of this example is that the reference to
RED
is also considered ambiguous,
because two distinct declarations are inherited. The fact that the two fields named
RED
happen to have the same type and the same unchanging value does not affect this
judgment.
Example 8.3-2. Re-inheritance of Fields
If the same field declaration is inherited from an interface by multiple paths, the field
is considered to be inherited only once. It may be referred to by its simple name
without ambiguity. For example, in the code:
interface Colorable {
int RED = 0xff0000, GREEN = 0x00ff00, BLUE = 0x0000ff;
}
interface Paintable extends Colorable {
int MATTE = 0, GLOSSY = 1;
}
class Point { int x, y; }
class ColoredPoint extends Point implements Colorable {}
class PaintedPoint extends ColoredPoint implements Paintable {
int p = RED;
}
the fields
RED
,
GREEN
, and
BLUE
are inherited by the class
PaintedPoint
both through its
direct superclass
ColoredPoint
and through its direct superinterface
Paintable
. The simple
names
RED
,
GREEN
, and
BLUE
may nevertheless be used without ambiguity within the
class
PaintedPoint
to refer to the fields declared in interface
Colorable
.
8.3.1. Field Modifiers
FieldModifiers:
FieldModifier
FieldModifiers FieldModifier