I'm writing a very basic app, extending the Swing JFrame. What are the differences between making an explicit reference:
public class LineTe开发者_Go百科st 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 (e.g. 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
精彩评论