Java 包(package)的概念及实例

  

包的作用

  • 1、把功能相似或相关的类或接口组织在同一个包中,方便类的查找和使用。

  • 2、如同文件夹一样,包也采用了树形目录的存储方式。同一个包中的类名字是不同的,不同的包中的类的名字是可以相同的,当同时调用两个不同包中相同类名的类时,应该加上包名加以区别。因此,包可以避免名字冲突。

  • 3、包也限定了访问权限,拥有包访问权限的类才能访问某个包中的类。

Java 使用包(package)这种机制是为了防止命名冲突,访问控制,提供搜索和定位

包的实例

  • 1、首先看一下我的文件tree:

    • assert tree
      .
      ├── TestAssert.class
      ├── TestAssert.java
      ├── Vector.java
      └── com
          └── bruceeckel
              └── tools
                  ├── Assert
                  │   ├── Assert.class
                  │   └── Assert.java
                  └── HelloWorld
                      ├── HelloWorld.class
                      └── HelloWorld.java
  • 2、看一下Assert的代码:

    • package com.bruceeckel.tools.Assert;
      
      public class Assert {
          private static void perr(String msg){
          System.err.println(msg);
          }
      
          public final static void is_true(boolean exp) {
              if(!exp) perr("Assertion failed");
              }
      
          public final static void is_false(boolean exp) {
              if(!exp) perr("Assertion failed");
              }
          public final static void is_true(boolean exp, String msg) {
              if(!exp) perr("Assertion failed: " + msg);
              }
          public final static void is_false(boolean exp, String msg) {
              if(!exp) perr("Assertion failed: " + msg);
              }
          }
  • 3、下面是helloworld包的代码:

    • package com.bruceeckel.tools.HelloWorld;
      
      public class HelloWorld {
          public void say(){
              System.out.println( "my name is zhangyin test " );
          }
      }
  • 下面是测试代码:
    • import com.bruceeckel.tools.HelloWorld.*;
      import com.bruceeckel.tools.Assert.*;
      
      public class TestAssert {
          public static void main(String[] args)
          {
              HelloWorld stu = new HelloWorld();
              stu.say();
              Assert.is_true((2 + 2) ==  5);
              Assert.is_false((1 + 1) ==  2);
              Assert.is_true((2 + 2) ==  5, "2 + 2 == 5");
              Assert.is_false((1 + 1) ==  2, "1 + 1 != 2");
          }
      }
  • 运行结果:

    

assert java TestAssert
my name is zhangyin test
Assertion failed
Assertion failed: 2 + 2 == 5

  上面的实际例子很清楚的解释了package的用法,具体的代码请参考:

https://github.com/DyLanCao/java_example/tree/master/base/assert

原文地址:https://www.cnblogs.com/dylancao/p/11994148.html