This section describes two types of 'import' statements: Single Type Import and On-Demand Type Import. 4 sample Java source files are provided to test 'import' statements.
Java offers two types of "import" statements:
1. Single Type Import: "import TypeName;" - It loads the definition of a single type immediately from
the specified package.
2. On-Demand Type Import: "import PackageName.*;" - It tells JVM to search this package for any missing type.
"javac" command processes there two different types of "import" statements differently. I wrote the following
4 source files.
1. ClsA.java:
/**
* ClsA.java
* Copyright (c) 2006 by Dr. Herong Yang, http://www.herongyang.com/
*/
package com.herong.util;
public class ClsA {
public void printInfo() {
System.out.println("Class: com.herong.util.ClsA");
}
}
2. ClsB.java:
/**
* ClsB.java
* Copyright (c) 2006 by Dr. Herong Yang, http://www.herongyang.com/
*/
package com.herong.util;
public class ClsB {
public void printInfo() {
System.out.println("Class: com.herong.util.ClsB");
}
}
3. ImportTestA.java:
/**
* ImportTestA.java
* Copyright (c) 2006 by Dr. Herong Yang, http://www.herongyang.com/
*/
import com.herong.util.*;
public class ImportTestA {
public static void main(String[] arg){
ClsA a = new ClsA();
a.printInfo();
ClsB b = new ClsB();
b.printInfo();
}
}
4. ImportTestB.java:
/**
* ImportTestB.java
* Copyright (c) 2006 by Dr. Herong Yang, http://www.herongyang.com/
*/
import com.herong.util.ClsA;
import com.herong.util.ClsB;
public class ImportTestB {
public static void main(String[] arg){
ClsA a = new ClsA();
a.printInfo();
ClsB b = new ClsB();
b.printInfo();
}
}
Read the following section to see how "javac" compilation tool processing "import" statements.