静态导入 ()

  如果说现在某一个类中定义的方法全部都属于static类型的方法,那么其他类要引用,可以不实例化直接进行调用。

传统做法:

public class MyMath {
    public static int add( int x , int y ) {
        return x + y ;        
    }
    public static int div( int x , int y ) {
        return x / y ;        
    }    
}

此时MyMath类中方法都是static类型的方法,随后在其他类使用这些方法:

public class TestDemo {

    public static void main(String[] args) {
        System.out.println("加法操作" + MyMath.add(10,20));
        System.out.println("除法操作" + MyMath.div(10,2));
    }
}

上述中,static方法可以不实例化直接调用使用,但是觉得写类名麻烦则可以使用静态导入方法。

静态导入方法使用:

package cn.mldn.utli;
// 将MyMath类中的全部static方法导入,现在这些方法就好比本类中定义的方法一样调用
import static cn.mldn.utli.MyMath.* ;
public class TestDemo {

    public static void main(String[] args) {
        System.out.println("加法操作" + add(10,20));
        System.out.println("除法操作" + div(10,2));
    }
}

从程序的整体便于理解的角度看,不适用类名称表示方法调用,则会影响可读性。

猜你喜欢

转载自www.cnblogs.com/wangyuyang1016/p/10903591.html
今日推荐