When should I write Static Methods?

后端 未结 8 829
梦如初夏
梦如初夏 2021-01-04 02:31

So I understand what a static method or field is, I am just wondering when to use them. That is, when writing code what design lends itself to using static methods and field

8条回答
  •  自闭症患者
    2021-01-04 02:56

    Static methods are usually useful for operations that don't require any data from an instance of the class (from this) and can perform their intended purpose solely using their arguments.
    A simple example of this would be a method Point::distance(Point a, Point b); that calculates the distance between two points and don't require an instance.

    Static fields are useful among others for constants that don't change all that often and are used by all the instances of a class.

提交回复
热议问题