包
包是对类、接口等的封装机制的体现,是一种对类或者接口等的很好的组织方式,比如:一个包中的类不想被其他包中的类使用。包还有一个重要的作用:在同一个工程中允许存在相同名称的类,只要处在不同的包中即可。
可以使用 import语句导入包
- import java.util.Date;
- public class Test {
- public static void main(String[] args) {
- Date date = new Date();
- // 得到一个毫秒级别的时间戳
- System.out.println(date.getTime());
- }
- }
- import java.util.*;
- public class Test {
- public static void main(String[] args) {
- Date date = new Date();
- // 得到一个毫秒级别的时间戳
- System.out.println(date.getTime());
- }
- }
- import static java.lang.Math.*;
- public class Test {
- public static void main(String[] args) {
- double x = 30;
- double y = 40;
- // 静态导入的方式写起来更方便一些.
- // double result = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
- double result = sqrt(pow(x, 2) + pow(y, 2));
- System.out.println(result);
- }
- }
操作步骤





- package com.bit.demo1;
- public class Computer {
- private String cpu; // cpu
- private String memory; // 内存
- public String screen; // 屏幕
- String brand; // 品牌
- public Computer(String brand, String cpu, String memory, String screen) {
- this.brand = brand;
- this.cpu = cpu;
- this.memory = memory;
- this.screen = screen;
- }
- public void Boot(){
- System.out.println("开机~~~");
- }
- public void PowerOff(){
- System.out.println("关机~~~");
- }
- public void SurfInternet(){
- System.out.println("上网~~~");
- }
- }
- package com.bite.demo2;
-
- import com.bite.demo1.Computer;
-
- public class TestComputer {
- public static void main(String[] args) {
- Computer p = new Computer("HW", "i7", "8G", "13*14");
- System.out.println(p.screen);
- // System.out.println(p.cpu); // 报错:cup是私有的,不允许被其他类访问
- // System.out.println(p.brand); // 报错:brand是default,不允许被其他包中的类访问
- }
- }
- // 注意:如果去掉Computer类之前的public修饰符,代码也会编译失败