java basic static import

Java basics-static import

In java, you can use import and directly import the method in the package with a prefix, such as the method in the Math package in the following example:

import java.lang.Math;  //import导入

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

        System.out.println(Math.max(2,8));

        System.out.println(java.lang.Math.max(2,8)); //直接加前缀

    }
}

In addition to these two, there is also a static import:

import static java.lang.Math.*;  //静态导入Math类中的所有方法

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

        /**
         * 	直接使用方法名即可
         * */
        System.out.println(max(2,8));  
        System.out.println(abs(-123));

    }
}

Static methods need to pay attention to the following:
1. The static import method must be static, otherwise an error will be reported.
2. If there are multiple static methods with the same name, it is easy to not know who to use. At this time, you must add the prefix of the method you need to use

import static java.lang.Math.*;  //静态导入Math类中的所有方法

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

        //下列的代码报错,和Math类中的max方法重名了,不知道使用哪个静态方法
        // System.out.println(max(2,8));
        
        //要想使用Math类里面的max()方法就必须加前缀,如下:
        System.out.println(Math.max(2,8));
		//没有重名的静态方法,直接使用方法名即可
        System.out.println(abs(-123));

    }
	
	//和Math类中的max方法重名
    public static void max(int a,int b){
    
    
		System.out.println("a为:" + a +",b为:"+ b);
    }
}

Although it is easier to write static imports, we do not recommend using it for this type.

Guess you like

Origin blog.csdn.net/weixin_47316336/article/details/109038198
Recommended