How to import java class?

Possible duplicate:
Import package. * vs import package.SpecificType

Is it possible:

import java.awt.* 

instead:

 import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; 

if both paths are correct, which one is better?

+6
java import
source share
4 answers

You can import a generic package, but it's better to be more explicit and import specific classes that you need. This helps prevent namespace conflicts and is much nicer.

In addition, if you use Eclipse and the shortcut CTRL + SHIFT + O, it automatically generates an explicit import, offering you an ambiguous import.

+14
source share

It will only import classes in java.awt, so you need to import java.awt.event as well:

 import java.awt.* import java.awt.event.*; 

The second method is likely to load fewer classes, but not save a lot of memory.

+7
source share

They are both good. The top one is less detailed, but the second one will allow you to be specific regarding the classes you import, avoiding collisions. Since most IDEs allow you to hide import statements, verbosity of the second is not a problem.

Consider

 import java.util.*; import java.awt.*; 

when you try to declare a List , you will have a collision between java.awt.List and java.util.List

+6
source share

That which is more explicit.

EDIT: The advantage of the second method is readability, no namespace conflicts, etc. But if you have hundreds of classes to import from a single package, it is better to move on to the first approach.

+4
source share

All Articles