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

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

    MyClass.staticMethod() makes it clear that you are calling a static (non-overrideable) method.

    this.staticMethod() misleads the reader into thinking that it is an instance method.

    staticMethod() is also on the misleading side (though I normally do it that way).

    If you think of people reading your code as unfamiliar with it you tend to try to make the code clearer, and this is a case where the code is clearer by having ClassName.method instead of instance.method.

提交回复
热议问题