Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 380
Michael Avatar asked Apr 27 '11 13:04

Michael


2 Answers

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 (e.g. java.util.List and java.awt.List) - in that case there is no alternative.

like image 96
Michael Borgwardt Avatar answered Oct 03 '22 23:10

Michael Borgwardt


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.

like image 31
Jesper Avatar answered Oct 03 '22 22:10

Jesper