zoukankan      html  css  js  c++  java
  • import vs static import

    静态引入(Static Import)是Java引入的特性,它允许在类中定义public static的成员(字段和方法),在使用时不用指定类名。此特性是在1.5版本中引入的。
    该功能提供了一种类型安全的机制,可以不必引用最初定义字段的类使用常量。它也有助于放弃创建常量接口:这是只定义了常量的接口,这种接口被认为是不合适的。
    这种机制被用来引入类的单个成员:

    import static java.lang.Math.PI;
    import static java.lang.Math.pow;

    或者类的所有静态成员:

    import static java.lang.Math.*;

    例如:

    public class HelloWorld {
        public static void main(String[] args) {
            System.out.println("Hello World!");
            System.out.println("Considering a circle with a diameter of 5 cm, it has:");
            System.out.println("A circumference of " + (Math.PI * 5) + " cm");
            System.out.println("And an area of " + (Math.PI * Math.pow(2.5,2)) + " sq. cm");
        }
    }

    上面的类可以改写成:

    import static java.lang.Math.*;
    import static java.lang.System.out;
    public class HelloWorld {
        public static void main(String[] args) {
            out.println("Hello World!");
            out.println("Considering a circle with a diameter of 5 cm, it has:");
            out.println("A circumference of " + (PI * 5) + " cm");
            out.println("And an area of " + (PI * pow(2.5,2)) + " sq. cm");
        }
    }

    歧义
    如果多个类中名称相同的静态成员被引入,编译器会抛出错误,因为它不能判定使用哪个类的成员。例如,下面代码会编译失败:

    import static java.lang.Integer.*;
    import static java.lang.Long.*;
    
    public class HelloWorld {
        public static void main(String[] args) {
            System.out.println(MAX_VALUE);
        }
    }

    MAX_VALUE是有歧义的,因为MAX_VALUE字段即是Integer的属性又是Long的属性。在字段前加上雷鸣可以消除歧义,但这样会造成静态引入冗余。

    参考文章
    http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html
    https://en.wikipedia.org/wiki/Static_import
    http://viralpatel.net/blogs/static-import-java-example-tutorial/

    如果觉得本文对您有帮助,请“打赏”,谢谢。
    您的鼓励,我的动力。
    微信 支付宝
  • 相关阅读:
    左偏树
    论在Windows下远程连接Ubuntu
    ZOJ 3711 Give Me Your Hand
    SGU 495. Kids and Prizes
    POJ 2151 Check the difficulty of problems
    CodeForces 148D. Bag of mice
    HDU 3631 Shortest Path
    HDU 1869 六度分离
    HDU 2544 最短路
    HDU 3584 Cube
  • 原文地址:https://www.cnblogs.com/zongzhankui/p/5875307.html
Copyright © 2011-2022 走看看