Java package (learning java programming language)

Write if you want 2021-01-21 23:24:15
java package learning java programming

Java Allow the use of packages (package) Organize classes into a collection . With the help of packages, you can easily organize your own code , And separate their own code from the code base provided by others .

The standard Java Class libraries are distributed in multiple packages , Include java.long、java.util and etc. . The standard Java Packages have a hierarchy . All standard Java The bags are all in java and javax In the package hierarchy .

1. Package name

The main reason to use a package is to ensure that the class name is unique . in fact , To ensure the absolute uniqueness of the package name , To use an Internet domain name ( This is obviously the only one ) Take the package name in reverse order , Then use different sub packages for different projects . for example , domain name, Write in reverse order , Get the package name com.xiang117. Then you can append a project name , Such as com.xiang117.corejava. If you're putting Employee Class in this bag , So this kind of “ Completely limited ” The name is com.xiang117.corejava.Employee.

From the compiler's point of view , There is no relationship between nested packages . for example ,java.util Bag and java.util.jar The bag has nothing to do with it . Each package is a separate collection of classes .

2. Class import

A class can use all the classes in its package , And the public classes in other packages (public class).
There are two ways to access public classes in another package :

  1. Use fully qualified names (fully qualified name), The package name is followed by the class name .
    java.time.LocalData today =;
  2. Use import sentence .

have access to import Statement to import a specific class or entire package .import Statement should be at the top of the resource file ( But in package After statement ).

import Statement is a simple way to refer to the classes in a package . Once used import sentence , When using classes , You don't have to write the full name of the class .

import The only advantage of a sentence is its simplicity . You can use a short name instead of a full package name to refer to a class .

You can use the following statement to import java.time All classes in the package . import java.time.*;
You can use LocalDate today =;
There is no need to prefix the package .

java.time.* Its grammar is relatively simple , There's no negative impact on the size of the code . Of course , If you can clearly indicate the imported class , It will make the readers of the code know more exactly which classes you are using .

It should be noted that , Only asterisks can be used (_) Import a package , They can't be used import java._ or import java._._ Import to java All packages for prefix .

You can import specific classes in a package : import java.time.LocalDate;

in the majority of cases , You can import only the packages you need , You don't have to think too much about them . But in the event of a naming conflict , Pay attention to the bag . for example ,java.util and java.sql All the bags have Date class . If you import these two packages into the program : import java.util.; import java.sql.;
Use... In the program Date Class time , A compilation error will occur : Date today; // Error--java.util.Date or java.sal.Date?
At this point, the compiler cannot determine which one the program is using Date class . You can add a specific import To solve this problem : import java.util.; import java.sql.; import iava.util.Date;
If these two Date Classes need to use , You need to prefix each class name with the full package name . java.util.Date deadline = new java.util.Date(); java.sql.Date today = new java.sql.Date();

Locating a class in a package is a compiler (compiler) The job of . Bytecode in a class file always references other classes with the full package name .

3. Static import

There is a kind of import Statement allows static methods and static fields to be imported , Not just classes .

If it's at the top of the source file , Add an instruction : import static java.lang.System.*;
You can use System Class static methods and static fields . Without prefixing the class name : out.println("Goodbye, World!"); // i.e., System.out exit(0); // i.e., System.exit

You can import specific methods or fields : import static java.lang.System.out;

actually , Is there a lot of Website monitoring Programmers want to abbreviate System.out or System.exit, It's doubtful . The code written in this way doesn't look very clear . however , sqrt(pow(x, 2) + pow(y, 2))
Looks like Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2))
Much clearer .

4. Add classes to the package

To put a class in a package , You have to put the package name at the beginning of the source file , That is, before defining the code of each class in this package . For example, in com.xiang017.corejava Add... To the bag Employee class :

package com.xiang017.corejava;

public class Employee




If it is not placed in the source file package sentence , The classes in this source file belong to _ Nameless bag (unnamed package)_. No name bag, no name bag .

import com.xiang017.javacore.*;

public class PackageTest {

public static void main(String[] args) {

Employee harry = new Employee("Harry Hacker", 50000, 1989, 10, 1);



Place the source file in a subdirectory that matches the full package name . for example ,com.xiang017.corejava All source files in the package should be placed in subdirectories com/xiang017/corejava in . The compiler places class files in the same directory structure . for example :

. ( Base directory )




To compile this program , Just switch to the base directory , And run the command : javac
The compiler will automatically look up the file com/xiang017/corejava/ And compile . The compiled result is as follows :

. ( Base directory )






To run this program , You need to execute the command in the base directory : java PackageTest

If The source file is not in the base directory , stay mycompany It's a bag , Such as :

.( Base directory )

|-- com/

|-- corejava/

| |--

| |-- Employe.class


|-- mycompany/


|-- PackageTest.class

Still compile and run classes from the base directory , Which contains com Directory of directories : javac com/mycompany/ java com.mycompany.PackageTest

We need to pay attention to , Compiler to file ( Extension with file separator .java The file of ) To operate . and Java Interpreter load class ( with . The delimiter ).

Warning : The compiler does not check the directory structure when compiling the source file . for example , Suppose there is a source file with the following instructions at the beginning : package com.mycompany;
Even if the source file is not in a subdirectory com/mycompany Next , You can also compile . If it doesn't depend on other packages , You can compile without compile errors . however , The final program will not run , Unless you first move all the class files to the correct location . If the package does not match the directory , The virtual machine can't find the class .

import com.xiang017.javacore.*;

public class PackageTest {

public static void main(String[] args) {

Employee harry = new Employee("Harry Hacker", 50000, 1989, 10, 1);

System.out.println("name=" + harry.getName() +

",salary=" + harry.getSalary() +

",hireDay=" + harry.getHireDay());




package com.xiang017.javacore;

import java.time.LocalDate;

import java.util.Objects;

public class Employee {

private String name;

private double salary;

private LocalDate hireDay;

public Employee(String name, double salary, int year, int month, int day) { = name;

this.salary = salary;

hireDay = LocalDate.of(year, month, day);


public String getName() {

return name;


public double getSalary() {

return salary;


public LocalDate getHireDay() {

return hireDay;


public void raiseSalary(double byPercent) {

double raise = salary * byPercent / 100;

salary += raise;



5. Package access

Marked as public Can be used by any class ; Marked as private Can only be used by the class that defines them . If not specified public or private, This part ( class 、 Method or variable ) Can be accessed by all methods in the same package .

A class without a tag modifier can only be accessed by other classes in the same package . For a class , This default is reasonable . however , It's not appropriate for variables , Variables must be explicitly marked as private, Otherwise, the package will be visible by default . This will destroy encapsulation .

By default , A package is not a closed entity . in other words , Anyone can add more classes to the package .

from 1.2 version ,JDK The implementer of has modified the class loader , Explicitly prohibit loading package names to “java.” The user-defined class at the beginning ! Of course , User defined classes don't benefit from this protection . Another mechanism makes JAR The file declares that the package is sealed (sealed), To prevent third parties from modifying , But this mechanism is out of date . Now it's time to use the module wrapper .

本文为[Write if you want]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云