在Java中,我什么时候应该用进口全*包,而不是单个对象从包? [英] In Java, when should I import whole packages with * instead of individual objects from the package?

查看:149
本文介绍了在Java中,我什么时候应该用进口全*包,而不是单个对象从包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一些缺点有语句,如进口android.view。*,而不是只进口其实我从视图包中使用的对象?它将使我编译Android应用程序的大小,如果我使用*?如果是的话,那么什么是决定是否与*或只是单个对象导入整个包的最佳实践?谢谢

Is there some disadvantage to having statements such as import android.view.* instead of just importing the objects I actually use from the view package? Will it make my compiled android application larger in size if I use the *? If yes, then what is best practice for deciding whether to import the whole package with * or just single objects ? Thanks

推荐答案

在他们的著作核心的Java卷1 ,作者指出

In their book Core Java Volume 1, the authors state that

java.util中。*语法是不那么单调乏味。它有code尺寸没有负面影响。
  但是,如果您导入类明确,你的code的读者都知道
  正是您所使用的类。

The java.util.* syntax is less tedious. It has no negative effect on code size. However, if you import classes explicitly, the reader of your code knows exactly which classes you use.

这是你需要担心的包的唯一情况是当你有一个名称冲突。例如,无论是java.util中和的java.sql包有Date类。现在假设你写的导入两个包的程序。
    的进口java.sql中。的*和
    的进口java.util中。的*
如果您现在尝试使用Date类,你会得到一个编译时错误。你必须,如果你想两者都使用他们使用完全合格的名称。

The only time that you need to worry about packages is when you have a name conflict. For example, both the java.util and java.sql packages have a Date class. Now suppose you write a program that imports both packages. import java.sql.* and import java.util.* If you try to use the Date class now, you will get a compile time error. You'll have to use fully qualified name if you want to use them both.

import语句的唯一好处是方便。它的不可以类似于C的#include指令在书中的Java的编程与语言(它有詹姆斯·高斯林作为它的作者之一),作者声明如下:

The only benefit of the import statements is convenience. It is not analogous to the #include directives in C. In the book The Java Programmin Language (It has James Gosling as one of its authors), the authors state the following,

导入语句简单地提供信息(您正在使用的类型的
  code)编译器;他们不会导致被包含文件到当前文件。

Import statements simply provide information (about the types you are using in your code) to the compiler; they don't cause files to be "included" into the current file.

我所推断从书本上的 Java语言规范的(由比尔·乔伊,詹姆斯·高斯林等人),和我上面提到的是,与野生卡import语句是所谓的类型导入点播宣言的。这告诉编译器,如果它发现它不知道,它应该看看由给定的包名称的导入点播的看到声明是否有该名称的成员。

What I have inferred from the books The Java Language Specification (By Bill Joy, James Gosling et. al), and the one I mentioned above is that the import statements with the wild-cards are called Type-Import-on-Demand Declaration. This tells the compiler that if it finds names that it doesn't know about, it should look at package given by the import-on-demand statement to see if it has a member by that name.

这篇关于在Java中,我什么时候应该用进口全*包,而不是单个对象从包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆