Why is it preferable to call a static method statically from within an instance of the method's class?

前端 未结 5 1509
自闭症患者
自闭症患者 2021-01-13 10:16

If I create an instance of a class in Java, why is it preferable to call a static method of that same class statically, rather than using this.method()?

I get a warn

5条回答
  •  温柔的废话
    2021-01-13 10:43

    Static methods are really not part of your instance - and it will not be able to access any of your instance variables anyway, so I would dare thinking it doesn't make a lot of sense calling it from the constructor.

    If your need to initialize static objects use

    private static List l = new ArrayList();   static { l.add("something"); }
    

    If you still need to call it its perfectly legal to call local static methods without prefixing your local class name, like this (no eclipse warning)

    public MyClass() { staticMethod(); }
    

提交回复
热议问题