简体   繁体   中英

Java: Use import or explicit package / class name?

I'm writing a very basic app, extending the Swing JFrame. What are the differences between making an explicit reference:

public class LineTest extends javax.swing.JFrame {
...

or importing the class beforehand:

import javax.swing.JFrame;

public class LineTest extends JFrame {
...

When (and why) would you use one technique over the other?

There is no real difference; the generated byte code will be exactly the same. An import statement is really just a way to tell the compiler "when I write JFrame , I actually mean javax.swing.JFrame ".

You might want to use fully-qualified package names if you have for example two classes with the same name in different packages. One common example from the standard library are the classes java.util.Date and java.sql.Date .

The only difference is in the source code. Using the fully qualified name leads to less readable code, so everyone uses imports pretty much exclusively. The only place where I've ever seen the fully qualified names used consistently is in generated code.

The only reason to use the fully qualified name in regular code is when you have to use two classes with the same simple name (eg java.util.List and java.awt.List ) - in that case there is no alternative.

For the compiler it doesn't make any difference. The disadvantage of using the full qualified name is that you would have to write it each time you are using the class. I only use the full qualified name if I have two classes with the same name in different packages. This way you can differ between those two classes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM