简体   繁体   English

Java:使用导入或显式 package / class 名称?

[英]Java: Use import or explicit package / class name?

I'm writing a very basic app, extending the Swing JFrame.我正在编写一个非常基本的应用程序,扩展 Swing JFrame。 What are the differences between making an explicit reference:明确引用之间有什么区别:

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

or importing the class beforehand:或预先导入 class :

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 ". import语句实际上只是告诉编译器“当我写JFrame时,我实际上是指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.如果您在不同的包中有两个具有相同名称的类,您可能希望使用完全限定的 package 名称。 One common example from the standard library are the classes java.util.Date and java.sql.Date .标准库中的一个常见示例是类java.util.Datejava.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.在常规代码中使用完全限定名称的唯一原因是当您必须使用具有相同简单名称的两个类时(例如java.util.Listjava.awt.List ) - 在这种情况下没有其他选择。

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.使用全限定名的缺点是每次使用 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这样你就可以在这两个类之间有所不同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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