Java Reference
In-Depth Information
interfaces of java.lang into every source fi le, so there is never any need to import types from
java.lang (although it is perfectly valid to do so).
The following program demonstrates an import statement that uses the wildcard to
import an entire package. The program uses the File , FileReader , BufferedReader , and
IOException classes, all found in the java.io package. The program reads a line of text
from a fi le named mydata.txt .
1. import java.io.*;
2.
3. public class ReadFromFile {
4. public static void main(String [] args) {
5. File file = new File(“mydata.txt”);
6. FileReader fileReader = null;
7. try {
8. fileReader = new FileReader(file);
9. BufferedReader in = new BufferedReader(fileReader);
10. System.out.println(in.readLine());
11. }catch(IOException e) {
12. e.printStackTrace();
13. }
14. }
15. }
Because nothing is actually included into your source fi le by the import keyword, using
the wildcard does not impact the size of your bytecode fi les. However, common practice
in Java is to avoid using the wildcard because it may lead to ambiguity when two packages
are imported that share a common class name. For example, the following code does not
compile because there is a class called AttributeList in both the javax.swing.text.html
.parser package and the javax.management package:
1. import javax.swing.text.html.parser.*;
2. import javax.management.*;
3.
4. public class ImportDemo {
5. public AttributeList a;
6. }
The ImportDemo class generates the following compiler error:
reference to AttributeList is ambiguous, both class
javax.management.AttributeList in javax.management and class
javax.swing.text.html.parser.AttributeList in
javax.swing.text.html.parser match
public AttributeList a;
Search WWH ::




Custom Search