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

后端 未结 2 374
再見小時候
再見小時候 2021-01-13 10:08

This might just be a question of personal taste and workflow, but in case it\'s more than that, I feel I should ask anyway.

In Java, what differences are there betwe

相关标签:
2条回答
  • 2021-01-13 11:02

    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.

    0 讨论(0)
  • 2021-01-13 11:06

    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.

    0 讨论(0)
提交回复
热议问题