天天看点

Java使用自定义包

包的声明和使用非常简单,在了解基本语法之后,下面通过一个案例演示在 Java 程序中声明包,以及不同包之间类的使用。

(1) 创建一个名为 com.dao 的包。

(2) 向 com.dao 包中添加一个 Student 类,该类包含一个返回 String 类型数组的 GetAll() 方法。Student 类代码如下:

  1. package com.dao;
  2. public class Student
  3. {
  4. public static String[] GetAll()
  5. {
  6. String[] namelist={"李潘","邓国良","任玲玲","许月月","欧阳娜","赵晓慧"};
  7. return namelist;
  8. }
  9. }

(3) 创建 com.test 包,在该包里创建带 main() 方法的 Test 类。

(4) 在 main() 方法中遍历 Student 类的 GetAll() 方法中的元素内容,在遍历内容之前,使用 import 引入 com.dao 整个包。完整代码如下:

  1. package com.test;
  2. import com.dao.Student;
  3. public class Test
  4. {
  5. public static void main(String[] args)
  6. {
  7. System.out.println("学生信息如下:");
  8. for(String str:Student.GetAll())
  9. {
  10. System.out.println(str);
  11. }
  12. }
  13. }

(5) 运行上一步骤的代码进行测试,最终的输出结果如下:

学生信息如下:
李潘
邓国良
任玲玲
许月月
欧阳娜
赵晓慧