When should I use static methods in a class and what are the benefits?

前端 未结 10 1436
孤独总比滥情好
孤独总比滥情好 2020-11-27 12:34

I have concept of static variables but what are the benefits of static methods in a class. I have worked on some projects but I did not make a method static. Whenever I need

10条回答
  •  醉酒成梦
    2020-11-27 12:56

    The only time you want to use a static method in a class is when a given method does not require an instance of a class to be created. This could be when trying to return a shared data source (eg a Singleton) or performing an operation that doesn't modify the internal state of the object (String.format for example).

    This wikipedia entry explains static methods pretty well: http://en.wikipedia.org/wiki/Method_(computer_science)#Static_methods

提交回复
热议问题