开发者

How to import java class? [duplicate]

开发者 https://www.devze.com 2022-12-20 14:03 出处:网络
This question already has answers here: Closed 12 year开发者_如何学Cs ago. Possible Duplicate: Import package.* vs import package.SpecificType
This question already has answers here: Closed 12 year开发者_如何学Cs ago.

Possible Duplicate:

Import package.* vs import package.SpecificType

Can I do:

import java.awt.*

instead of:

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

if both ways are correct which one is better?


You can import the general package, but it's better to be more explicit and import the specific classes you need. It helps to prevent namespace collision issues and is much nicer.

Also, if you're using Eclipse and the shortcut CTRL+SHIFT+O it will automatically generate the explicit imports, prompting you for the ambiguous imports.


It will import only classes in java.awt, so you have to import java.awt.event too:

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

Second method will probably load less classes, but won't save you much memory.


They are both good. The top one is less verbose, but the second will allow you to be specific about the classes you import, allowing you to avoid collisions. As most IDEs will allow you to hide import statements, the verbosity of the second is not really an issue.

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


One that is more explicit.

EDIT : Advantage of the second method is readability, no conflict of namespaces, etc. But if you have hundred classes to import from one package you better go with the first approach.

0

精彩评论

暂无评论...
验证码 换一张
取 消