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

前端 未结 5 1475
自闭症患者
自闭症患者 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:45

    In addition to the other answers which have mentioned making it clear you're using a static method, also note that static methods are not polymorphic, so being explicit with the class name can remove any confusion as to which method is going to be called.

    In the code below, it's not entirely obvious that b.test() is going to return "A" if you're expecting the polymorphism of a non-static method:

    public class TestStaticOverride
    {
      public static void main( String[] args )
      {
        A b = new B();
        System.out.println( "Calling b.test(): " + b.test() );
      }
    
      private static class A
      {
        public static String test() { return "A"; }
      }
    
      private static class B extends A
      {
        public static String test() { return "B"; }
      }
    }
    

    If you change the code to B b = new B(); it will print out "B".

    (Whether it's ever a good idea to "override" static methods is probably a discussion for another day...)

提交回复
热议问题