包和导包

48 阅读1分钟
什么是包呢?
    包其实就是文件夹 作用:对类进行分类管理
包的定义格式: 
    格式:package 包名;
    注意:包名一般是公司域名反写,并且多级包用.分开 
    举例:www.itheima.com 
    范例:package com.itheima;

image.png

itheima_01下的student类
    package com.itheima_01;
    public class Student { 
        public void study() { 
        System.out.println("好好学习天天向上");
        }
    }
同一个包下类的使用
    package com.itheima_01;
    public class StudentTest { 
        public static void main(String[] args) { 
            Student s = new Student(); 
            s.study();
        }
    }
不同包下类的使用
    package com.itheima_02;
    public class StudentTest { 
        public static void main(String[] args) { 
            com.itheima_01.Student s = new com.itheima_01.Student(); s.study();
            com.itheima_01.Student s2 = new com.itheima_01.Student(); s2.study();
        } 
    }
使用不同包下的类时,使用的时候要写类的全路径,写起来太麻烦了。 为了简化带包的操作,Java就提供了导包的功能。

导包的格式:

格式:import 包名;
范例:import com.itheima.Student;
    package com.itheima_02;
    import com.itheima_01.Student; 
    //Alt+Enter 快捷键导包
public class StudentTest { 
    public static void main(String[] args) { 
        Student s = new Student(); s.study();
        Student s2 = new Student(); s2.study();
        //com.itheima_01.Student s = new com.itheima_01.Student(); s.study();
        //com.itheima_01.Student s2 = new com.itheima_01.Student(); s2.study();
    } 
}
导包的三种方式:
1. 手动导包
2. 快捷键导包
3. 写一个类,写一部分的时候,如果给出了对应的提示,回车后会自动导包