A small knowledge point - Java static import

A small knowledge point - Java static import
insert image description here

introduce

What is static import ? It is the ability to import static methods and static fields.

import class

When it comes to importing classes in Java, you must be familiar with it, for example:

import java.util.Scanner;

public class Demo {
    
    
    public static void main(String[] args) {
    
    

        // 构造 Scanner 对象
        Scanner sc = new Scanner(System.in);

        // 创建字符串
        String s = sc.nextLine();

        // 输出字符串
        System.out.println(s);

    }
}

insert image description here

Import static methods and static fields

importAfter importing the static methods and static fields of the System class, you can write as follows:

import java.util.Scanner;
import static java.lang.System.*;

public class Demo {
    
    
    public static void main(String[] args) {
    
    

        // 构造 Scanner 对象
        Scanner sc = new Scanner(in);

        // 创建字符串
        String s = sc.nextLine();

        // 输出字符串
        out.println(s);

    }
}

insert image description here
After importing the static methods and static fields of the System class, you can see that it can run normally Systemwithout .

Second, you can also import specific methods or fields.
insert image description here
However, the static import of Java seems to be unfavorable for some situations that need to import many classes. After all, there are many libraries in Java. If a method is heavy, an error will be reported.

Guess you like

Origin blog.csdn.net/qq_21484461/article/details/123713678