Alex Rivera | Logout

Any difference between class imports and package imports in Java?

Asked 2009-10-12T10:54:49.940
16

In Java we can either import single classes as well as the whole set of classes (a package).

As an example

import java.util.*

includes

import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Iterator;
import java.util.Map;

Other than the length of the code, are there any specific advantages of using the each approach in any manner? Memory allocation? Performance?

Edit
Report

2 Answers

2

Performing an explicit import is safer at compile time, since there's no possibility of a class conflict. e.g.

import java.sql.*;
import java.util.*;

causes a problem if you're trying to use a Date class (i.e. from which package ?).

But other than that, there's no performance or memory aspect. It's purely a compile-time issue.

answered 2009-10-12T10:58:54.360
2

The advantage of importing using a '*' is that it is fewer lines of code, and less typing. This is more important if you do your coding with a "dumb" text editor rather than an IDE than can use ellipses to hide imports and can add imports semi-automatically.

The disadvantages of importing using '*' are:

  • You get imported class name collisions occasionally; e.g. when some class name is used for classes in different packages and you import both of them.
  • You cannot see a classes explicit dependencies by looking at the imports. But this is less important if your IDE can show you the dependencies some other way.
answered 2009-10-12T11:00:50.620

Your Answer