In Java, when should I import whole packages with * instead of individual objects from the package?

大城市里の小女人 提交于 2019-12-13 07:36:26

问题


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


回答1:


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

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.

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.

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,

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.

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.




回答2:


You need to know that import isn't loading anything. The class loader does that.

All import does is let you use short class names instead of long ones in your code (e.g. Connection instead of java.sql.Connection). It will not affect the size of your Android app at all.



来源:https://stackoverflow.com/questions/10592951/in-java-when-should-i-import-whole-packages-with-instead-of-individual-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!