必学Java基础-包和import讲解

131 阅读2分钟

一、生活案例

邮寄快递:中国.广州.白云区.****小区.6号楼.3单元.601房.赵四

历史:常山赵子龙

二、包的作用

为了解决重名问题(实际上包对应的就是盘符上的目录)

解决权限问题

三、创建包

包名定义

(1)名字全部小写

(2)中间用.隔开

(3)一般都是公司域名倒着写 : com.jd com.lanson

(4)加上模块名字:

com.jd.login com.jd.register

(5)不能使用系统中的关键字:nul,con,com1---com9.....

(6)包声明的位置一般都在非注释性代码的第一行:

四、导包问题

<pre class="prettyprint hljs java" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, &quot;Courier New&quot;, monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">//声明包:
package com.lanson;

import com.lanson3.Person; //导包:就是为了进行定位

import java.util.Date;

/**
 * @Auther: lanson
 */
public class Test {
    //这是一个main方法,是程序的入口:
    public static void main(String[] args) {
        new Person();
        new Date();
        new java.sql.Date(1000L);//在导包以后,还想用其他包下同名的类,就必须要手动自己写所在的包。
        new Demo();
    }
}</pre>

#### 总结:

(1)使用不同包下的类要需要导包: import

.

.

; 例如:import java.util.Date;

(2)在导包以后,还想用其他包下同名的类,就必须要手动自己写所在的包。

(3)同一个包下的类想使用不需要导包,可以直接使用。

(4)在java.lang包下的类,可以直接使用无需导包:

(5)IDEA中导包快捷键:alt+enter

可以自己设置自动导包

(6)可以直接导入*:

(7)在Java中的导包没有包含和被包含的关系:

设置目录平级的格式(不是包含和被包含的显示):

五、静态导入

<pre class="prettyprint hljs gradle" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, &quot;Courier New&quot;, monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">package com.lanson;
//静态导入:
import static java.lang.Math.*;
//导入:java.lang下的Math类中的所有静态的内容
/**
 * @Auther: lanson
 */
public class Test {
    //这是一个main方法,是程序的入口:
    public static void main(String[] args) {
        System.out.println(random());
        System.out.println(PI);
        System.out.println(round(5.6));
    }
    //在静态导入后,同一个类中有相同的方法的时候,会优先走自己定义的方法。
    public static int round(double a){
        return 1000;
    }
}</pre>