search
HomeJavajavaTutorialHow to use Java packages

What is a package

A package is a way of organizing classes.

The main purpose of using a package is to ensure the uniqueness of a class.

For example, You write a Test class in the code. Then your colleague may also write a Test class. If there are two classes with the same name, they will conflict, causing the code to fail to compile.

1. Import the package Class

Java has provided many ready-made classes for us to use

①: For example, printing an array:

public class TestDemo{
    public static void main(String[] args) {
        int[] array = {1,2,3,4,5};
        System.out.println(Arrays.toString(array));
    }
}

To use Arrays, you need to import the package, see the picture:

How to use Java packages

If the top line of code is not written, an error will be reported. See the picture:

How to use Java packages

Then how to import the above As for the package, when we write the Arrays code, IDEA will automatically pop up the options for you to choose. If you select the first item and press Enter, it will help you import the package. Look at the picture:

How to use Java packages

②: Another example:

Date is a class that defines dates and is also written by the Java class library

public class TestDemo {
    public static void main(String[] args) {
        java.util.Date date = new java.util.Date();//在我们不导包时候手写
        // 得到一个毫秒级别的时间戳
        System.out.println(date.getTime());
   }
}

You can use java.util.Date to introduce the Date class in the java.util package.

But this way of writing is more troublesome. At this time, you can use the above way of writing, and you can use the import statement to import the package.

import java.util.Date;
public class TestDemo {
    public static void main(String[] args) {
        Date date = new Date();
        // 得到一个毫秒级别的时间戳
        System.out.println(date.getTime());
   }
}

Note:

You can import a specific class, but you cannot import a specific package

How to use Java packages

: Import the util package, report an error

How to use Java packages

: Import specific classes

③: Another example:

If you need to use other classes in java.util, you can use import java.util.*

import java.util.*;
public class TestDemo {
    public static void main(String[] args) {
        Date date = new Date();
        // 得到一个毫秒级别的时间戳
        System.out.println(date.getTime());
   }
}

How to use Java packages

: No error is reported. This * can be understood as a wildcard character, which means importing all classes under this package.

Question: Under util There are many classes, should they all be imported at once? No, when it comes to Java processing, it will deal with whoever is needed.

④: But we recommend explicitly specifying the class name to be imported. Otherwise, conflicts are still prone to occur.

Example:

import java.util.*;
import java.sql.*;
public class TestDemo {
    public static void main(String[] args) {
        // util 和 sql 中都存在一个 Date 这样的类, 此时就会出现歧义, 编译出错
        Date date = new Date();
        System.out.println(date.getTime());
   }
}
// 编译出错
Error:(5, 9) java: 对Date的引用不明确
  java.sql 中的类 java.sql.Date 和 java.util 中的类 java.util.Date 都匹配

In this case You need to use the complete class name

Note:

import is very different from C's #include. C must #include to introduce the content of other files, but Java does not. Import is just for writing It is more convenient when coding. Import is more similar to C's namespace and using

Knowledge points

The difference between import and package

package: "package", refers to: class The package in which it is located

import: "Introduction" refers to: the classes required in the imported class

If we want to use the code in some Java class libraries, we need to import it through import

2. Static import

Use import static to import static methods and fields in the package.

①Example:

import static java.lang.System.*;
public class Test {
    public static void main(String[] args) {
        out.println("hello");
   }
}

This way System.out.println( "hello"); can be written as out.println("hello");

② Another example:

import static java.lang.Math.*;
public class TestDemo {
    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);
   }
}

Math. can be removed when writing the code.

3. Put the class into the package

Basic rules:

Add a package statement at the top of the file to specify which package the code is in.

The package name needs to be specified as unique as possible, usually using the reverse form of the company's domain name (for example, com.xuexiao.demo1).

The package name must match the code path. For example, create com. xuexiao.demo1 package, then there will be a corresponding path com/xuexiao/demo1 to store the code.

If a class does not have a package statement, the class will be placed in a default package.

Operation steps:

1) First create a new package in IDEA: Right-click src -> New-> Package

How to use Java packages

2) In the pop-up Enter the package name in the dialog box, for example com.xuexiao.demo1 and click Enter

How to use Java packages

## 3) Create a class in the package, right-click the package name-> New-> ; class, and then enter the class name

How to use Java packages

4) At this point you can see that the directory structure on our disk has been automatically created by IDEA

How to use Java packages

5) At the same time, we also saw that at the top of the newly created Test.java file, a package statement appeared

How to use Java packages

4.包的访问权限控制

 我们已经了解了类中的 public 和 private. private 中的成员只能被类的内部使用.

如果某个成员不包含 public 和 private 关键字, 此时这个成员可以在包内部的其他类使用, 但是不能在包外部的类使 用.

举例:

下面的代码给了一个示例. Demo1 和 Demo2 是同一个包中, Test 是其他包中.

 Demo1.java

package com.bili.demo;
public class Demo1 {
    int value = 0;
}

Demo2.java

package com.bili.demo; 
public class Demo2 { 
 public static void Main(String[] args) { 
 Demo1 demo = new Demo1(); 
 System.out.println(demo.value); 
 } 
}

// 执行结果, 能够访问到 value 变量
10

Test.java

import com.bili.demo.Demo1; 
public class Test { 
 public static void main(String[] args) { 
 Demo1 demo = new Demo1(); 
 System.out.println(demo.value); 
 } 
} 
// 编译出错
Error:(6, 32) java: value在com.bili.demo.Demo1中不是公共的; 无法从外部程序包中对其进行访问

5.常见的系统包

1. java.lang:系统常用基础类(String、Object),此包从JDK1.1后自动导入。

2. java.lang.reflect:java 反射编程包;

3. java.net:进行网络编程开发包。

4. java.sql:进行数据库开发的支持包。

5. java.util:是java提供的工具程序包。(集合类等) 非常重要

6. java.io:I/O编程开发包。

The above is the detailed content of How to use Java packages. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

How does platform independence simplify deployment of Java applications?How does platform independence simplify deployment of Java applications?May 02, 2025 am 12:15 AM

Java'splatformindependenceallowsapplicationstorunonanyoperatingsystemwithaJVM.1)Singlecodebase:writeandcompileonceforallplatforms.2)Easyupdates:updatebytecodeforsimultaneousdeployment.3)Testingefficiency:testononeplatformforuniversalbehavior.4)Scalab

How has Java's platform independence evolved over time?How has Java's platform independence evolved over time?May 02, 2025 am 12:12 AM

Java's platform independence is continuously enhanced through technologies such as JVM, JIT compilation, standardization, generics, lambda expressions and ProjectPanama. Since the 1990s, Java has evolved from basic JVM to high-performance modern JVM, ensuring consistency and efficiency of code across different platforms.

What are some strategies for mitigating platform-specific issues in Java applications?What are some strategies for mitigating platform-specific issues in Java applications?May 01, 2025 am 12:20 AM

How does Java alleviate platform-specific problems? Java implements platform-independent through JVM and standard libraries. 1) Use bytecode and JVM to abstract the operating system differences; 2) The standard library provides cross-platform APIs, such as Paths class processing file paths, and Charset class processing character encoding; 3) Use configuration files and multi-platform testing in actual projects for optimization and debugging.

What is the relationship between Java's platform independence and microservices architecture?What is the relationship between Java's platform independence and microservices architecture?May 01, 2025 am 12:16 AM

Java'splatformindependenceenhancesmicroservicesarchitecturebyofferingdeploymentflexibility,consistency,scalability,andportability.1)DeploymentflexibilityallowsmicroservicestorunonanyplatformwithaJVM.2)Consistencyacrossservicessimplifiesdevelopmentand

How does GraalVM relate to Java's platform independence goals?How does GraalVM relate to Java's platform independence goals?May 01, 2025 am 12:14 AM

GraalVM enhances Java's platform independence in three ways: 1. Cross-language interoperability, allowing Java to seamlessly interoperate with other languages; 2. Independent runtime environment, compile Java programs into local executable files through GraalVMNativeImage; 3. Performance optimization, Graal compiler generates efficient machine code to improve the performance and consistency of Java programs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.