What is the gain from declaring a method as static

后端 未结 9 597
别跟我提以往
别跟我提以往 2020-12-07 10:35

I\'ve recently been looking through my warnings in Eclipse and come across this one:

\"static

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-07 11:22

    There is no concept with optimization here.

    A static method is static because you explicitly declare that method doesn't rely on any instance the enclosing class just because it doesn't need to. So that Eclipse warning, as stated in documentation:

    When enabled, the compiler will issue an error or a warning for methods which are private or final and which refer only to static members.

    If you don't need any instance variable and your method is private (can't be called from outside) or final (can't be overriden) then there is no reason to let it be a normal method instead that a static one. A static method is inherently safer even just because you are allowed to do less things with it (it doesn't need any instance, you don't have any implicit this object).

提交回复
热议问题