Using private static methods [duplicate]

2019-01-16 18:25发布

This question already has an answer here:

What do you think about using private static methods?

Personally, I prefer using a static private method to non-static as long as it does not require access to any instance fields.

But I heard that this practice violates OOP principles.

Edit: I am wondering from style prospective of view, not performance.

7条回答
▲ chillily
2楼-- · 2019-01-16 19:08

Private static methods can for example operate on private static members of their class. This can be utilized to encapsulate and unify certain class specific operations.

The major drawback of using static methods is in my opinion the fact that one throws away the possibility to override. Since classes in Java are not like, let's say, classes in Smalltalk, you can not override static methods.

Since your question relates to private static methods, overriding is out of option anyway.

I tend to use static methods only in case of utility classes (like java.lang.Math) or patterns like the Singleton pattern. All of these require a higher visibility than private, because they represent services provided by their class to others.

Final thought: If you have one or more private static methods, think about extracting them to a dedicated utility class and making them public. Even better, make them instance methods and use the Singleton pattern.

查看更多
登录 后发表回答