为什么java需要静态类_java – 为什么OOP中静态类的最佳实践有所不同?
我目前正在閱讀有關
Java最佳實踐的內容,我發現根據
this book,我們必須支持非靜態的靜態類.我記得在C#最佳實踐中,我們必須根據Dennis Doomen的C#3.0,4.0和5.0編碼指南來避免這種情況:
AV1008 – Avoid static classes
With the exception of extension method containers static classes very often lead to badly designed code. They are also very difficult,if not impossible,to test in isolation unless you’re willing to use some very hacky tools. Note If you really need that static class,mark it as static so that the compiler can prevent instance members and instantiating your class. This relieves you of creating an explicit private constructor.
我在C# answer和Java answer中找到了這兩個用于避免靜態類的時間,但僅僅是出于好奇 – C#和Java都是OOP語言,為什么它與最佳實踐完全不同呢?
更新:
我不能從Java書中復制這么多頁面,但底線是:
If you declare a member class that does not require access to an
enclosing
instance,always put the static modifier in its declaration,making it a static
rather than a nonstatic member class. If you omit this modifier,each instance will
have an extraneous reference to its enclosing instance. Storing this reference costs
time and space,and can result in the enclosing instance being retained when it
would otherwise be eligible for garbage collection (Item 6). And should you ever
need to allocate an instance without an enclosing instance,you’ll be unable to do
so,as nonstatic member class instances are required to have an enclosing instance.
A common use of private static member classes is to represent components of
the object represented by their enclosing class.
它只是關于性能嗎?
請注意,這個問題更多的是關于靜態類和OOP,而不是Java和C#之間的差異.
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的为什么java需要静态类_java – 为什么OOP中静态类的最佳实践有所不同?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python图片横向合并_[宜配屋]听图
- 下一篇: fiddler安装_Fiddler的安装