Datasheet

You cannot statically import data from a class that is inside the default package. The class must be
located inside a named package. Also, static attributes and methods can conflict. For example, following
are two classes (located in
Colors.java and Fruits.java) containing static constants:
package MyConstants;
public class Colors {
public static int white = 0;
public static int black = 1;
public static int red = 2;
public static int blue = 3;
public static int green = 4;
public static int orange = 5;
public static int grey = 6;
}
package MyConstants;
public class Fruits {
public static int apple = 500;
public static int pear = 501;
public static int orange = 502;
public static int banana = 503;
public static int strawberry = 504;
}
If you write a class that tries to statically import data on both these classes, everything is fine until you
try to use a static variable that is defined in both of them:
import static MyConstants.Colors.*;
import static MyConstants.Fruits.*;
public class StaticTest {
public static void main(String args[])
{
System.out.println(“orange = “ + orange);
System.out.println(“color orange = “ + Colors.orange);
System.out.println(“Fruity orange = “ + Fruits.orange);
}
}
The seventh line of the program causes the following compiler error. The identifier orange is defined in
both
Colors and Fruits, so the compiler cannot resolve this ambiguity:
StaticTest.java:7: reference to orange is ambiguous, both variable orange in
MyConstants.Colors and variable orange in MyConstants.Fruits match
System.out.println(“orange = “ + orange);
In this case, you should explicitly qualify the conflicting name with the class where it is defined. Instead
of writing
orange, write Colors.orange or Fruits.orange.
23
Chapter 1: Key Java Language Features and Libraries
05_777106 ch01.qxp 11/28/06 10:43 PM Page 23