Java static imports

前端 未结 4 1251
借酒劲吻你
借酒劲吻你 2021-02-01 04:25

Just by experiment I discovered that Java non static methods overrides all same named methods in scope even at static context. Even without allowing parameter overloading. Like<

4条回答
  •  情歌与酒
    2021-02-01 05:04

    If you try following similar looking code then you will not get any compiler error

    import static java.util.Arrays.sort;
    public class StaticImport {
        public void bar(int... args) {
            sort(args); // will call Array.sort
        }
    }
    

    The reason this compiles and yours doesn't is that the toString() (or any other method defined in class Object) are still scoped to Object class because of Object being the parent of your class. Hence when compiler finds matching signature of those methods from Object class then it gives compiler error. In my example since Object class doesn't have sort(int[]) method hence compiler rightly matches it with the static import.

提交回复
热议问题