Java的import与package机制

版权声明:本文为博主原创文章,转载请注明出处哦。 https://blog.csdn.net/timo1160139211/article/details/79890689

Java的import与package机制

Java的import与package机制,控制着java程序复杂的文件结构,并且使其有条不紊的相互协作,互不冲突。

import

JAVA的import对于编程人员来说,节省了大量了代码去声明类的全名,比如:

java.lang.String str = "hello world";
java.util.List list = ...

每次用都需要声明类的全名,这实在太不人性化了。于是sun推了import机制,每次使用某个类时,只要我们用import事先指明是哪个包下的类,那么在这个java文件中使用的该类,都是我们import指明好的那个,当然也就不用声明全名,直接用该类类名即可。
也就是这样的:

import java.lang.String;

String str = "hello world";

有的朋友会发现,我们其实每次用String的时候都没有声明import java.lang.String,对的。因为lang包下的类实在太常用,于是sun为我们默认引入lang包下的类。

这样的作用可以和c的#include、c++的namespace对比着去记忆。不过他们的作用并不完全一样。

上面提到的 import java.lang.String; 是 import的一种, 称之为:

单类型导入(single-type-import)

还有一种是:

按需类型导入(type-import-on-demand)

例如:

import java.util.*;

List list = ...
Date date = 

用一个通配符 * 表明引入其包下的所有类。
它的作用如单类型导入重叠起来一样。

那么,又有朋友会问了。那么为了简单起见,我们直接用 * 按需类型导入所有包不就万事大吉了吗,还用单类型导入干嘛。其实,并不是。我们从 import引入算法角度分析:

import引入算法:
import引入类的时候,假如我们声明的是其全称如java.lang.String;那么编译器会直接去去寻找java/lang/String的类文件。找不到则编译通不过,报出错误标记String找不到(lang包下的不会出此问题,仅举例)。
如果我们使用按需类型导入,如java.util.*; java.awt.*去声明,那么我们用到List的时候,程序会进行排列组合,找出所有List有可能存在的包。也就是java.util.List;java.awt.List;都有可能,当编译器找到第一个List类文件的时候并不会停止继续匹配。而是继续寻找,然后发现awt下也有一个List,编译器此时会报错:


Error:(8, 5) java: reference to List is ambiguous
  both interface java.util.List in java.util and class java.awt.List in java.awt match

这样就遇到了二义性错误。在大型应用当中,用到的第三方包越多,这种请客越要容易发生。

所以,为了程序编译更快,避免冲突,我们尽量用单类型导入。

我们看源码的时候,sun的老前辈 一般不用*来导包。

package

我们来看官方给出的定义:

To make types easier to find and use, to avoid naming conflicts, and to control access, programmers bundle groups of related types into packages.

Definition: A package is a grouping of related types providing access protection and name space management. Note that types refers to classes, interfaces, enumerations, and annotation types. Enumerations and annotation types are special kinds of classes and interfaces, respectively, so types are often referred to in this lesson simply as classes and interfaces.

package site.gaoyisheng;

public class Hello(){
}

有了import,那么我这个类该归属那个包下呢?package用来声明在哪个包下。

那么,这个Hello.java必须要放如到site/gaoyisheng/Hello.java这个路径下,否则你在别处使用Hello类时,编译器编译后在执行时,将会报告NoClassDefFoundError。

优点:

  • You and other programmers can easily determine that these types are related.
  • You and other programmers know where to find types that can provide graphics-related functions.
  • The names of your types won’t conflict with the type names in other packages because the package creates a new namespace.
  • You can allow types within the package to have unrestricted access to one another yet still restrict access for types outside the package.

参考资料:
https://docs.oracle.com/javase/tutorial/java/package/packages.html
<Java深度历险>王森
https://blog.csdn.net/alphafish/article/details/652330
http://www.cnblogs.com/yqskj/articles/2097836.html

猜你喜欢

转载自blog.csdn.net/timo1160139211/article/details/79890689