天天看点

Java 静态导入

Java静态导入就是通过给导入包名中添加一个 static 关键字,从而直接通过方法名使用方法。这样的好处是无须使用类名调用,或者新建一个对象来调用其中的方法。

要求对象中所有方法都是静态方法。

版本要求:jdk1.5

示例:

未使用静态导入,通过

类名.方法名

调用

新建一个

MathTest

类,添加一个加法和减法的方法

package testp;

public class MathTest {

    public static int add(int a, int b) {
        return a + b;
    }

    public static int sub(int a, int b) {
        return a - b;
    }

}
           

创建一个

TestCode

类,并添加

main

方法

package testp;

import testp.MathTest.*;

public class TestCode {

    public static void main(String[] args) {
        int a = 3; 
        int b = 4;
        System.out.println(MathTest.add(a, b));
        System.out.println(MathTest.sub(a, b));
    }

}
           

调试代码结果如下

Java 静态导入

使用静态导入

MathTest

类保持不变,和上面一样,

TestCode

类代码修改如下:

package testp;

import static testp.MathTest.*;

public class TestCode {

    public static void main(String[] args) {
        int a = 3; 
        int b = 4;
        System.out.println(add(a, b));
        System.out.println(sub(a, b));
    }

}
           

运行结果相同;

Java 静态导入

使用静态导入犹如在该类中创建静态方法一样便利;

转自:https://zhuanlan.zhihu.com/p/35756938