Java: Difference between initializing by constructor and by static method?

試著忘記壹切 提交于 2019-12-01 06:36:32

The difference is a static factory method is more flexible. It can have all sorts of ways to return an instance. It can do other side stuff. It can have a more descriptive name. It can be invoked by its simple name (e.g. foo(args)) by static import or inheritance.

The constructor call is more certain - the caller knows exactly what's happening - a new instance of that exact class is created.

There are both advantages and disadvantages of static factory methods.

Advantages

  • Descriptive, meaningful names.
  • When invoked they can decide whether to return a new instance
  • They can return an object of any subtype of the return type
  • They reduce the verbosity of creating parameterized type instances

Disadvantages

  • If you provide only static factory methods, classes without public or protected constructors cannot be subclassed
  • They are not readily distinguishable from other static methods

Source: Effective Java, Second Ed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!