When should I write Static Methods?

后端 未结 8 832
梦如初夏
梦如初夏 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:53

    You should use static methods whenever you have a function that does not depend on a particular object of that class.

    There is no harm in adding the static keyword: it will not break any of the code that referred to it. So for example, the following code is valid whether or not you have the 'static' keyword:

    class Foo
    {
        public Foo(){}
        public static void bar(){}  // valid with or without 'static'
        public void nonStatic(){ bar(); }
    }
    
    ...
    Foo a = new Foo();
    a.bar();
    

    So you should add 'static' to whatever methods you can.

提交回复
热议问题