How 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:
If the top line of code is not written, an error will be reported. See the picture:
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:
②: 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
: Import the util package, report an error
: 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()); } }
: 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
2) In the pop-up Enter the package name in the dialog box, for example com.xuexiao.demo1 and click Enter
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip
