static vs non static

后端 未结 4 1808
梦谈多话
梦谈多话 2020-12-19 04:21

Until few weeks back, I thought I understand when to make fields and methods static or non-static. For example, when a field (say object of another

4条回答
  •  庸人自扰
    2020-12-19 04:35

    Static fields is a concept you should really think carefully about before using it as a method to increase the efficiency of your application.

    As you know when static modifier is included in a field , no instance of the class is required for it to be used. And as a result it has a the same value for the entire application. On one hand it can lead to many bugs in multi-threaded read/write environment if you don't properly serialize the access, on the other hand it is good thing if you trying to create singleton pattern (A field with a value that do not change during the life time of the application and therefor do not need to be GC)

    By and large you should avoid read/write static fields, it will introduce more bugs into your application. Having the same value across many instances of the same class is not considered a good use case for static field in OO design. Not because it is less or more efficient but because it breaks the concept of encapsulation.

提交回复
热议问题