The import Statement in Java Programming

The import Statement in Java Programming

Previous Home Next

 

To use a package's classes inside a Java source file, 
it is safe to import the classes from the package with an import declaration.
import java.awt.event.|*;

The import directive tells the compiler where to look for the class definitions 
when it comes upon a class that it cannot find in the default java.lang package.


import mypackage.*;
import mypackage.extrapackage.*;
import java.applet.*;

indicate that classes can be found in the mypackage and mypackage.extrapackage
packages and also that the Applet class can be found in the java.applet package.
 

The first import statement gives the full package path name for the Applet class in the packages included with thestandard JVM. Then when the compiler sees just Applet in the class definition title, it will know where to find it.
In the next two import statements, we see the "*" wildcard character used for the classes in the mypackage and mypackage. extrapackage packages. This indicates that these packages hold multiple classes and the compiler should look here if it cannot find a class in the core packages.

The wildcard only applies to classes, not to sub-packages. That is, mypackage.* only refers to the classes in the package,not to the sub-directory extrapackage. You must import each package name separately.

If the packages that you import happened to have two classes with the same name, to use one of them you will need to give the fully qualified name so that the compiler will know which of these classes you want to use.

 
 import java.applet.Applet;
import mypackage.*;
import mypackage.extrapackage.*;

public class TestApplet extends Applet
{
public static void init (String [] arg) {
TestA a = new TestA (4);
TestB b = new TestB (31.3);
if( c.flag)
System.out.println ("a.i = "+a.i);
else
System.out.println ("a.x = "+b.x);
}
// Paint message in Applet window.
public void paint(java.awt.Graphics g) {
g.drawString ("TestCpplet",20,20);
}
}


Previous Home Next